package com.example.onlinemonitoring.comCenter;

import com.example.onlinemonitoring.Util.CRC16;
import com.example.onlinemonitoring.Util.CommPortManager;
import com.example.onlinemonitoring.Util.HexUtil;
import com.example.onlinemonitoring.Util.IEEE754Utils;
import com.example.onlinemonitoring.Util.LanguageManager;
import com.example.onlinemonitoring.autoRun.ComRunner;
import com.example.onlinemonitoring.dao.OilconfigMapper;
import com.example.onlinemonitoring.dao1.TOLM_VarMapper;
import com.example.onlinemonitoring.model.Appdevice;
import com.example.onlinemonitoring.model.Oilconfig;
import com.example.onlinemonitoring.model.Oilhistory;
import com.example.onlinemonitoring.model.Oilsensor;
import com.example.onlinemonitoring.model1.TOLM_Var;
import com.example.onlinemonitoring.serviceImpl.AppdeviceServiceImpl;
import com.example.onlinemonitoring.serviceImpl.OilsensorServiceImpl;
import com.fasterxml.jackson.databind.deser.SettableAnyProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.context.annotation.Scope;
import ch.qos.logback.classic.pattern.Util;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.net.SocketException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

/**
 * 油色谱
 */
@Service("oilCom")
@Scope("prototype")
public class OilCom extends CommPortManager {
    @Autowired
    private OilsensorServiceImpl oilserviceimpl;
    @Autowired
    private OilconfigMapper oilconfigmapper;
    @Autowired
    private AppdeviceServiceImpl Appdeviceserviceimpl;
    @Autowired
    LanguageManager languageManager;
    @Autowired
    private TOLM_VarMapper tolm_varmapper;
    public int[] wStatus = new int[300];// 每个地址的当前下发命令
    public int[] wBKPara = new int[300];// 每个地址的包数量
    public int[] wBKNum = new int[300];// 每个地址待请求的包序号
    public int[] wBKResend = new int[300];
    public StringBuilder wpk = new StringBuilder();// 每个地址待请求的包序号
    int Threshold_0 = 500; // 波峰阈值（下限）1000 <波形顶点的阈值，不同气体乘以不同系数>
    int Threshold_1 = 120; // 波宽阈值（下限）80 <从起点到终点的数据个数>
    int Threshold_2 = 25; // 噪声阈值（上限）25
    int Threshold_3 = 5; // 斜率阈值（下限）5
    int Element_Number = 7; // 气体成分个数
    int Window_Size = 500; // 时域矩形窗宽度
    boolean isoilstand = false;
    long lasttime = 0;
    int MAX_GAS_CNT = 7;
    String[] gasstr = new String[] { "H2", "CO", "CH4", "CO2", "C2H4", "C2H6", "C2H2" };
    float start[] = new float[] { 1000, 1300, 1500, 3000, 4500, 5600, 7500 };
    float end[] = new float[] { 1300, 1500, 2500, 4000, 5600, 6800, 8600 };
    float f_H2 = 0;
    float f_CO = 0;
    float f_CH4 = 0;
    float f_CO2 = 0;
    float f_C2H4 = 0;
    float f_C2H6 = 0;
    float f_C2H2 = 0;
    int addridx = 0;
    // 锁对象
    public Object lock = new Object();

    public Object getLock() {
        return lock;
    }

    public void setLock(Object lock) {
        this.lock = lock;
    }

    public void setwStatus(int status, int index) {
        this.wStatus[index] = status;
    }

    HashMap<Integer, List<Double>> wdev = new HashMap<>();
    // 命令类型
    public final static int CMD_HEART = 0x10; // 心跳包
    public final static int CMD_DATA = 0x11; // 数据包（包数量及长度）
    public final static int CMD_MST = 0x4B; // 环境、微水
    public final static int CMD_RECORD = 0x50; // 采样数据
    public final static int CMD_WADDR = 0x2E; // 写地址
    public final static int CMD_RADDR = 0x2F; // 读地址
    public final static int CMD_WSAMPLE = 0x23; // 写采样周期
    public final static int CMD_RSAMPLE = 0x24; // 读采样周期
    public final static int CMD_GETTIME = 0x15; // 读取时间
    public final static int CMD_SETTIME = 0x16; // 同步时间
    public final static int CMD_WSAMPLENumber = 0x25; // 写采样点
    public final static int CMD_RSAMPLENumber = 0x26; // 读采样点
    public final static int CMD_WORK_START = 0x17; // 启动自动流程
    public final static int CMD_WORK_STOP = 0x18; // 停止自动流程
    public final static int CMD_SAMPLE_START = 0x1D; // 启动采样
    public final static int CMD_SAMPLE_STOP = 0x1E; // 停止采样
    public final static int CMD_RESET = 0x28; // 复位装置
    public final static int YNGAS_PATR = 50; // 启动采样
    public final static int YNGAS_CNT = 10; // 停止采样
    public final static int YNGAS_VPARA = 3; // 复位装置
    public StringBuilder simulatestr = new StringBuilder();

    @Override
    public void receiveDatas(String str) {
        switch (ad.getBrand()) {
            case "1":
                recvDir(str);
                break;
            case "3":
                recvOilDf(str);
                break;
            default:
                break;
        }
    }

    @Async("threadPool")
    public void startSendThread(Appdevice Appdevice) throws Exception {
        switch (Appdevice.getBrand()) {
            case "1":
                requestDir(Appdevice);
                break;
            case "2":
                readdatabase(Appdevice);
                break;
            case "3":
                requestDf(Appdevice);
                break;
            default:
                break;
        }
    }

    private void recvDir(String str) {
        byte[] bt = HexUtil.hexString2Bytes(str);
        String addrstr = str.substring(4, 6);
        Integer addrint = parseHex4(addrstr);
        if (addrint <= 0)
            return;
        reSend[addrint] = 0;
        oilserviceimpl.UpdateStatus(ad, addrint, 0);
        setText(" <" + languageManager.getLan().getAddress() + "：" + addrint + ""
                + languageManager.getLan().getCommand()
                + ":"
                + bt[3] + ">... "
                + languageManager.getLan().getInspectionSuccess() + "......." + str);
        switch (bt[3]) {
            case CMD_MST:// 环境微水
                CMD_MST(str, bt, addrint);
                break;
            case CMD_HEART:// 心跳包
                CMD_HEART(str, bt, addrint);
                break;
            case CMD_DATA:// 数据包（包数量及长度）
                CMD_DATA(str, bt, addrint);
                break;
            case CMD_RECORD:// 采样数据
                CMD_RECORD(str, bt, addrint);
                break;
            case CMD_WORK_START:// 启动自动流程
                CMD_WORK(str, bt, addrint);
                break;
            case CMD_WORK_STOP:// 停止自动流程
                CMD_WORK(str, bt, addrint);
                break;
            case CMD_RADDR:// 读地址
                CMD_WORK(str, bt, addrint);
                break;
            case CMD_WADDR:// 写地址
                CMD_WORK(str, bt, addrint);
                break;
            case CMD_RSAMPLENumber:// 读采样点
                CMD_WORK(str, bt, addrint);
                break;
            case CMD_WSAMPLENumber:// 写采样点
                CMD_WORK(str, bt, addrint);
                break;
            case CMD_RSAMPLE:// 读采样周期
                CMD_WORK(str, bt, addrint);
                break;
            case CMD_WSAMPLE:// 写采样周期
                CMD_WORK(str, bt, addrint);
                break;
            case CMD_GETTIME:// 读取时间
                CMD_WORK(str, bt, addrint);
                break;
            case CMD_SETTIME:// 同步时间
                CMD_WORK(str, bt, addrint);
                break;
            case CMD_RESET:// 复位装置
                CMD_WORK(str, bt, addrint);
                break;
            case CMD_SAMPLE_START:// 启动采样
                CMD_WORK(str, bt, addrint);
                break;
            case CMD_SAMPLE_STOP:// 停止采样
                CMD_WORK(str, bt, addrint);
                break;
            default:
                break;
        }
    }

    private void CMD_WORK(String str, byte[] bt, Integer addrint) {
        controllerRet = str;
    }

    private void CMD_RECORD(String str, byte[] bt, Integer addrint) {
        if (wBKNum[addrint] >= wBKPara[addrint]) {// 所有数据包接收完成，开始分析谱图
            Oilsensor os = new Oilsensor();
            os.setStationid(ad.getStationid());
            os.setDevicegroup(ad.getDevicegroup());
            os.setDeviceaddr(addrint);
            Oilsensor os1 = oilserviceimpl.getModel(os);
            boolean issim = false;
            if (os1.getSimulate() != 0) {
                setText("" + languageManager.getLan().getStandardStart() + "...");
                simfun(addrint);
                os.setLastorigindata(simulatestr.toString());
            } else {
                os.setLastorigindata(wpk.toString());
                issim = true;
            }
            if (oilserviceimpl.Update(os, false) == 0) {
                setText(languageManager.getLan().getUpdateGraphFailed()
                        + languageManager.getLan().getNoMonitoringPointInDatabase() + (addrint)
                        + " ！ "
                        + languageManager.getLan().getPleaseAddMonitoringPointFirst()
                        + "！");
                return;
            }
            wpk.delete(0, wpk.length());
            dataTransform(addrint, issim);
            wBKNum[addrint] = 0;
            addridx++;
            wStatus[addrint] = CMD_HEART;// 转回心跳包
            return;
        }
        wBKResend[addrint]++;
        if (wBKResend[addrint] > 100) {
            writeAppendFile(System.getProperty("user.dir") + "\\error.txt",
                    "" + languageManager.getLan().getPacket() + "" + wBKNum[addrint] + ""
                            + languageManager.getLan().getError()
                            + "："
                            + str);
            wBKNum[addrint]++;
            wBKResend[addrint] = 0;
            return;
        }
        int len = bt.length;
        // 校验
        if (len != 109) {
            setText("" + languageManager.getLan().getAddress() + "<" + addrint + ">"
                    + languageManager.getLan().getIncorrectPacketLength()
                    + "！");
            return;
        }
        if ((bt[0] & 0xFF) != 0x7F) {
            setText("" + languageManager.getLan().getAddress() + "<" + addrint + ">"
                    + languageManager.getLan().getIncorrectPacketHeaderKeyword() + "！");
            return;
        }
        if ((bt[len - 1] & 0xFF) != 0x0D) {
            setText("" + languageManager.getLan().getAddress() + "<" + addrint + ">"
                    + languageManager.getLan().getIncorrectPacketFooterKeyword() + "！");
            return;
        }
        String datas = str.substring(2, str.length() - 4);
        byte[] bdata = hexStringToBytes(datas);
        if (CRC8_MAXIM(bdata, 0, bdata.length) != (bt[len - 2] & 0xFF)) {
            setText("" + languageManager.getLan().getAddress() + "<" + addrint + ">"
                    + languageManager.getLan().getPacketChecksumError()
                    + "！");
            return;
        }

        wBKResend[addrint] = 0;
        wBKNum[addrint]++;
        // 处理采样数据
        if (wdev.get(addrint) == null) {
            setText("" + languageManager.getLan().getAddress() + "<" + addrint + ">"
                    + languageManager.getLan().getPacketsReceivedButNotInspected() + "！");
            return;
        }
        String str1 = "";
        for (int i = 0; i < 20; i++) {
            Double data = Double.valueOf(parseHex8(str.substring(14 + i * 10, 22 + i * 10)));
            wdev.get(addrint).add(data);
            str1 += data + ",";
            wpk.append(data + ",");
        }
        setText("" + languageManager.getLan().getAddress() + "<" + addrint + ">"
                + languageManager.getLan().getPacketData()
                + "："
                + str1);
        try {
            Date currentDate = new Date();
            SimpleDateFormat dateFormat = new SimpleDateFormat("MMdd");
            String formattedDate = dateFormat.format(currentDate);
            writeAppendFile(System.getProperty("user.dir") + "\\O" + addrint + "D" + formattedDate + ".txt", str1);// O1D0126
        } catch (Exception e) {

        }
    }

    // 数据处理
    public void dataTransform(Integer addrint, boolean simulate) {
        Oilsensor target = new Oilsensor();
        target.setStationid(ad.getStationid());
        target.setDevicegroup(ad.getDevicegroup());
        target.setDeviceaddr(addrint);
        Oilsensor os = oilserviceimpl.getModel(target);
        Example example = new Example(Oilconfig.class);
        Example.Criteria criteria = example.createCriteria();
        if (ad.getStationid() != null) {
            criteria.andEqualTo("stationid", ad.getStationid());
        }
        if (ad.getDevicegroup() != null) {
            criteria.andEqualTo("devicegroup", ad.getDevicegroup());
        }
        if (addrint != null) {
            criteria.andEqualTo("deviceaddr", addrint);
        }
        List<Oilconfig> ol = oilconfigmapper.selectByExample(example);
        if (ol == null || ol.size() == 0) {
            setText("" + languageManager.getLan().getAddress() + "<" + addrint + ">"
                    + languageManager.getLan().getConfigurationInformationMissing() + "！！");
            return;
        }
        if (os == null) {
            setText(languageManager.getLan().getNoMonitoringPointInDatabase() + (addrint) + " ！ "
                    + languageManager.getLan().getPleaseAddMonitoringPointFirst() + "！");
            return;
        }
        if (os.getLastorigindata() == null || os.getLastorigindata().equals("")) {
            return;
        }
        String[] oristr = os.getLastorigindata().split(",");
        int length = oristr.length;
        double[] f_origData = new double[length];
        double[] f_origData1 = new double[length];
        int nf = 0, iGas = 0;
        int iItem, iObj, iPStart = 0;
        int wsize[] = new int[length * 2]; // = new int[length * 2];
        int count[] = new int[length]; // = new int[length];
        double f_difData[] = new double[length];// = new double[length];
        double f_bufData[] = new double[length];// = new double[length];
        double f_newData[] = new double[length];// = new double[length];
        double ratio = 0.49;

        for (int i = 0; i < oristr.length; i++) {
            f_origData[i] = Double.parseDouble(oristr[i]);
            f_origData1[i] = Double.parseDouble(oristr[i]);
        }
        // 平滑滤波
        for (int i = 0; i < 7; i++) {
            DFilter(f_difData, f_origData, oristr.length, 7 + i * 2);
            for (int j = 0; j <= oristr.length - 1; j++)
                f_origData[j] = f_difData[j];
        }
        for (int i = 0; i < oristr.length; i++)
            f_origData[i] = (int) (f_origData[i] + 0.5);

        String ss = "";
        for (int i = 0; i < oristr.length; i++) {
            ss += f_origData[i] + ",";
        }

        // 数据压缩(去掉连续数值相同的点)
        int length_1 = DDataCompact(f_bufData, count, f_origData, length);

        // 调整色谱数据压缩后对应的屏幕尺寸
        DWindowSize(wsize, count, length_1, 500);

        double aFac[] = { 0.6, 1.0, 0.75 };// 0.6 0.7 0.75
        double aThr[] = { 1.0, 1.0, 1.0 };
        int len = length_1 / 3;
        aThr[0] = DAdaptThreshold(f_bufData, 0, len, count, aFac[0]);
        aThr[1] = DAdaptThreshold(f_bufData, len, len, count, aFac[1]);
        aThr[2] = DAdaptThreshold(f_bufData, len * 2, len, count, aFac[2]);

        // 提取色谱数据的基线
        DBaseLine(f_newData, f_bufData, count, wsize, length_1, aThr);

        // 对压缩数据进行扩展还原
        int length_2 = DDataExpand(f_bufData, f_newData, count, length_1);

        for (iItem = 0; iItem <= length_2 - 1; iItem++) {
            f_newData[iItem] = f_origData[iItem] - f_bufData[iItem];
            count[iItem] = 1;
            f_bufData[iItem] = 0.0;
        }

        String ss1 = "";
        for (int i = 0; i < length_2 - 1; i++) {
            ss1 += f_newData[i] + ",";
        }

        SNPeak f_peak[] = new SNPeak[7];
        SNElement f_elem[] = new SNElement[MAX_GAS_CNT];
        for (int i1 = 0; i1 < MAX_GAS_CNT; i1++) {
            f_elem[i1] = new SNElement();
        }
        SYN_Device pDevice = new SYN_Device();
        // [第1步]复位气体参数
        for (iGas = 0; iGas < 7; iGas++) {
            pDevice.pGas[iGas] = new SYN_Gas();
            pDevice.pGas[iGas].fPeakPos = 0;
            pDevice.pGas[iGas].fDensity = 0;
            pDevice.pGas[iGas].fPeakArea = 0;
            pDevice.pGas[iGas].iVarType = -1;
            for (int ipgas = 0; ipgas < 3; ipgas++) {
                pDevice.pGas[iGas].pPara[ipgas] = new SYN_GasPara();
            }
            pDevice.pGas[iGas].pPara[0].fPeakHeight = ol.get(iGas).getHeight2();
            pDevice.pGas[iGas].pPara[1].fPeakHeight = ol.get(iGas).getHeight3();
            pDevice.pGas[iGas].pPara[2].fPeakHeight = ol.get(iGas).getHeight4();
            pDevice.pGas[iGas].pPara[0].fScale = ol.get(iGas).getCof2();
            pDevice.pGas[iGas].pPara[1].fScale = ol.get(iGas).getCof3();
            pDevice.pGas[iGas].pPara[2].fScale = ol.get(iGas).getCof4();
            pDevice.pGas[iGas].randomCof = isnull(ol.get(iGas).getCof5());
            if (ol.get(iGas).getStart() == null || ol.get(iGas).getEnd() == null) {
                setText("" + languageManager.getLan().getAddress() + "<" + addrint + ">"
                        + languageManager.getLan().getFrameNotAddedCannotDetermineConcentration() + "");
                return;
            }
        }
        int pNum = DPeakSplit(f_peak, f_newData, count, length_2, ol, f_elem, pDevice);
        for (int fe = 0; fe < f_elem.length; fe++) {
            updatePdevice(pDevice, f_elem, fe);
        }
        String processdata = "";
        for (int fbi = 0; fbi < f_newData.length; fbi++) {
            processdata += f_newData[fbi] + ",";
        }
        // 标定↓↓↓↓
        if (isoilstand) {// 如果判断是手动标定的数据
            for (iGas = 0; iGas < 7; iGas++) {
                pDevice.pGas[iGas].fDensity = isnull(ol.get(iGas).getOilstandard());
            }
        }
        isoilstand = false;// 归位，防止多台油色谱乱
        // 模拟数据上下浮动↓↓↓↓
        if (os.getSimulate() != 0 || (os.getSimulateauto() != 0 && !simulate)) {// 如果是手动或者自动
            for (iGas = 0; iGas < 7; iGas++) {
                float cof5 = isnull(ol.get(iGas).getCof5());
                float cof6 = isnull(ol.get(iGas).getCof6());
                pDevice.pGas[iGas].fDensity *= (Math.random() * (cof5 * 2 - 2) - cof5 + 2) * cof6;
                if (pDevice.pGas[iGas].fDensity < 0) {
                    pDevice.pGas[iGas].fDensity = 0;
                }
            }
        }
        // 不同浓度下的系数↓↓↓↓
        for (iGas = 0; iGas < 7; iGas++) {
            if (ol.get(iGas).getHeight1() > pDevice.pGas[iGas].fDensity) {
                pDevice.pGas[iGas].fDensity = pDevice.pGas[iGas].fDensity * ol.get(iGas).getCof1()
                        + ol.get(iGas).getPcof1();
            } else if (ol.get(iGas).getHeight1() < pDevice.pGas[iGas].fDensity
                    && pDevice.pGas[iGas].fDensity < ol.get(iGas).getHeight2()) {
                pDevice.pGas[iGas].fDensity = pDevice.pGas[iGas].fDensity * ol.get(iGas).getCof2()
                        + ol.get(iGas).getPcof2();
            } else if (ol.get(iGas).getHeight2() < pDevice.pGas[iGas].fDensity
                    && pDevice.pGas[iGas].fDensity < ol.get(iGas).getHeight3()) {
                pDevice.pGas[iGas].fDensity = pDevice.pGas[iGas].fDensity * ol.get(iGas).getCof3()
                        + ol.get(iGas).getPcof3();
            } else if (ol.get(iGas).getHeight3() < pDevice.pGas[iGas].fDensity
                    && pDevice.pGas[iGas].fDensity < ol.get(iGas).getHeight4()) {
                pDevice.pGas[iGas].fDensity = pDevice.pGas[iGas].fDensity * ol.get(iGas).getCof4()
                        + ol.get(iGas).getPcof4();
            }
        }

        target.setLasth2((float) pDevice.pGas[0].fDensity);
        target.setLastco((float) pDevice.pGas[1].fDensity);
        target.setLastch4((float) pDevice.pGas[2].fDensity);
        target.setLastco2((float) pDevice.pGas[3].fDensity);
        target.setLastc2h4((float) pDevice.pGas[4].fDensity);
        target.setLastc2h6((float) pDevice.pGas[5].fDensity);
        target.setLastc2h2((float) pDevice.pGas[6].fDensity);
        target.setLastelem(pDevice.iDevStr);
        target.setLastprocesseddata(processdata);
        double TotHyd = pDevice.pGas[2].fDensity + pDevice.pGas[4].fDensity + pDevice.pGas[5].fDensity
                + pDevice.pGas[6].fDensity;
        target.setLasttothyd((float) TotHyd);
        target.setLastcommunicationstatus(0);
        target.setLastdatatime(new Date());

        target.setLasto2((ol.get(7).getOilstandard() * ((float) Math.random() * 2 + 9) / 10) * ol.get(7).getCof5()
                + ol.get(7).getPcof6());
        target.setLastn2((ol.get(8).getOilstandard() * ((float) Math.random() * 2 + 9) / 10) * ol.get(8).getCof5()
                + ol.get(8).getPcof6());

        UpdateAndAdd(os, target, simulate, ol.get(0).getOvercount());
    }

    public String testcurve(double[] cur) {
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < cur.length; i++) {
            s.append(cur[i] + ",");
        }
        return s.toString();
    }

    public String testcurve1(int[] cur) {
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < cur.length; i++) {
            s.append(cur[i] + ",");
        }
        return s.toString();
    }

    class SYN_GasPara {
        int iStart; // 峰起点
        int iEnd; // 峰终点
        int iPeakPos; // 峰顶点
        double fScale; // 系数
        double fPeakHeight; // 峰高（样气标定峰高）
    }

    // 气体参数
    class SYN_Gas {
        // 出峰顺序 - 数据库变量按照 H2 CO CH4 CO2 C2H4 C2H2 C2H6 的顺序排列，但出峰顺序因装置而异，进行调整后的顺序
        int iPeakIdx;
        int iVarType;// 变量类型（H2 CO CH4 CO2 C2H4 C2H2 C2H6）-- 此排序与数据库一致，永恒不变
        // 根据谱图计算
        double fPeakPos; // 峰值点
        double fDensity; // 浓度
        double fPeakArea; // 峰面积
        double fPeakHeight;// 峰高（当前采样峰高，保存时赋值给SYN_GasPara对应的fPeakHeight）
        double randomCof; // 随机值
        // 标定参数
        SYN_GasPara pPara[] = new SYN_GasPara[3];
    }

    // 设备参数
    class SYN_Device {
        int iAddr;
        int iDevId;// 设备ID
        String iDevStr = "";
        SYN_Gas pGas[] = new SYN_Gas[7];
    }

    // 搜索气体峰参数
    int SearchPeakPara(int iObj, SNPeak f_Peak[], double f_pData[], int iStart, int length) {
        int iStatus = 0;
        int iPeak = 0, iWidth = 0;
        boolean bEnd = false;
        double dTopDot = 0, dLowDot = 0; // 峰尖、峰谷值

        for (int iItem = iStart; iItem < (length - 5); iItem++) {
            switch (iStatus) {
                case 0: // 寻找上升沿
                    if ((f_pData[iItem + 1] > f_pData[iItem + 0]) && (f_pData[iItem + 2] > f_pData[iItem + 0]) &&
                            (f_pData[iItem + 15] > f_pData[iItem + 1]) && (f_pData[iItem + 30] > f_pData[iItem + 2])
                            && f_pData[iItem] > 0) {
                        iWidth = 1;
                        iStatus = 1;
                        dTopDot = f_pData[iItem];
                        f_Peak[iObj].start = iItem;
                    }
                    break;

                case 1:// 寻找峰顶点
                    iWidth += 1;
                    dLowDot = f_pData[iItem];// 下降沿的值与此参数比较

                    if ((f_pData[iItem] < dTopDot) && (f_pData[iItem + 1] < dTopDot) && (f_pData[iItem + 2] < dTopDot)
                            && (f_pData[iItem + 3] < dTopDot))
                        iStatus = 2;
                    else
                        dTopDot = f_pData[iItem];
                    break;

                case 2:// 寻找峰谷
                    if (0 == f_pData[iItem])// 找到值为0的点，说明到谷低
                    {
                        bEnd = true;
                        iPeak += 1;
                        f_Peak[iObj].length = iWidth;
                    } else if ((length - iItem) < 7) {
                        do {
                            if (f_pData[iItem] > 0)
                                iWidth += 1;
                            else
                                break;

                        } while (++iItem < length);

                        bEnd = true;
                        iPeak += 1;
                        f_Peak[iObj].length = iWidth;
                    } else if (f_pData[iItem + 1] >= f_pData[iItem] && f_pData[iItem + 2] >= f_pData[iItem] &&
                            f_pData[iItem + 3] >= f_pData[iItem] && f_pData[iItem + 4] >= f_pData[iItem]
                            && (dTopDot - dLowDot) / dTopDot >= 0.85)// 有些波丰谷非0点，此比值到达85%页认为一个完整峰
                    {
                        bEnd = true;
                        iPeak += 1;
                        f_Peak[iObj].length = iWidth;
                    } else if (f_pData[iItem + 1] >= f_pData[iItem] && f_pData[iItem + 2] >= f_pData[iItem] &&
                            f_pData[iItem + 3] >= f_pData[iItem] && f_pData[iItem + 4] >= f_pData[iItem]
                            && (dTopDot - dLowDot) / dTopDot < 0.85)// 认为此气体存在两个峰
                    {
                        // iPeak += 1; //重新寻找峰顶点
                        iWidth += 1;
                        iStatus = 1;
                        dTopDot = 0;
                    } else {
                        iWidth += 1;
                        dLowDot = f_pData[iItem];
                    }
                    break;
                default:
                    break;
            }

            if (bEnd) {
                if (iWidth < Threshold_1)// 宽度不够(起点到终点)
                {
                    bEnd = false;
                    iPeak = 0;
                    iWidth = 0;
                    iStatus = 0;
                } else if ((dTopDot - f_pData[f_Peak[iObj].start]) < Threshold_2)// 高度不够
                {
                    bEnd = false;
                    iPeak = 0;
                    iWidth = 0;
                    iStatus = 0;
                } else {
                    return iPeak;
                }
            }
        }

        return 0;
    }

    // 计算色谱气体峰高位置
    int DLocation(double f_elemData[], int count[], int start, int length) {
        int iItem, iObj;
        double fH;

        iObj = start;
        fH = f_elemData[iObj];
        for (iItem = start + 1; iItem <= start + length - 1; iItem++) {
            if (f_elemData[iItem] > fH) // fH记录峰高（即最大值），j记录峰高在压缩序列中的所在位置
            {
                iObj = iItem;
                fH = f_elemData[iObj];
            }
        }

        return iObj;

    }

    // 计算色谱单峰面积（累加法）
    double DArea0(double f_elemData[], int start, int length) {
        double fA = 0.01;

        for (int iItem = start; iItem <= start + length - 1; iItem++)
            fA += f_elemData[iItem];

        return fA;
    }

    // 计算色谱单峰面积（峰高*峰宽法）
    double DArea1(double f_elemData[], int count[], int start, int length) {
        int fW = DHalfWidth(f_elemData, count, start, length);
        int fL = DLocation(f_elemData, count, start, length);
        double fH = f_elemData[fL];

        return (fH * fW);
    }

    // 色谱峰左半侧面积百分比
    // double DLobeRatio(double f_elemData[], int count[], int start, int length) {
    // int loc = DLocation(f_elemData, count, start, length);

    // double a1 = DArea0(f_elemData, count, start, loc - start + 1);

    // double a2 = DArea0(f_elemData, count, start, length);

    // return (a1 / a2);
    // }

    // 计算压缩序列中某位置点对应在原始数据序列中的位置
    int DCount(int count[], int loc) {
        int iItem, tmp = 0;

        for (iItem = 0; iItem <= loc; iItem++)
            tmp += count[iItem];

        return (tmp - 1);

    }

    // 计算色谱峰半峰宽
    int DHalfWidth(double f_elemData[], int count[], int start, int length) {
        int fW = 0;
        int loc = DLocation(f_elemData, count, start, length);
        double fThr = f_elemData[loc] / 2;

        for (int iItem = start; iItem <= start + length - 1; iItem++) {
            if (f_elemData[iItem] >= fThr)
                fW += count[iItem];

        }

        return fW;

    }

    // 计算包含气体个数，并记录各气体峰在压缩数据序列中的起点、长度和峰顶信息
    int DElementCheck(SNElement f_Element[], int st, double f_elemData[], int count[], int start, int length) {
        int iT = 0;
        int iObj = 0;
        int iItem = 0;
        int f_cnt[] = new int[7500]; // = new int[length];
        double f_dif[] = new double[7500];// = new double[length];
        f_cnt[0] = count[start];
        f_dif[0] = 0;
        for (iItem = 1; iItem <= length - 1; iItem++) {
            f_cnt[iItem] = f_cnt[iItem - 1] + count[start + iItem];
            f_dif[iItem] = f_elemData[start + iItem] - f_elemData[start + iItem - 1];

            if (0 != count[start + iItem])
                f_dif[iItem] = f_dif[iItem] / count[start + iItem];
        }

        f_Element[st].start = 0;

        for (iItem = 0; iItem <= length - 2; iItem++) {
            if (f_dif[iItem + 1] < 0 && f_dif[iItem] > 0) // 峰顶
            {
                if (f_cnt[iItem] - f_cnt[iT] >= 30 && f_elemData[iItem + start] - f_elemData[iT + start] >= 300) {
                    f_Element[st + iObj].length = iItem;
                    iT = iItem;
                    iObj++;
                } else {
                    if (iObj > 0) {
                        f_Element[st + iObj].start = 0;
                        iObj--;
                    }

                    iT = f_Element[st + iObj].length;
                }
            } else if (f_dif[iItem + 1] > 0 && f_dif[iItem] < 0) // 峰谷
            {
                if (f_cnt[iItem] - f_cnt[iT] >= 30 && f_elemData[iT + start] - f_elemData[iItem + start] >= 300) {
                    f_Element[st + (iObj + 1) / 2].start = iItem;
                    iT = iItem;
                    iObj++;
                } else {
                    if (iObj > 0)
                        iObj--;

                    f_Element[st + iObj].length = 0;
                    iT = f_Element[st + iObj].start;
                }
            }
        }

        // 计算各气体成分在压缩后数据序列中的起始和终止位置
        if (iObj <= 1) {
            f_Element[st].start = start;
            f_Element[st].length = length;
            f_Element[st].end = f_Element[st].start + f_Element[st].length - 1;
            return 1;
        } else {
            for (iItem = 0; iItem <= (iObj - 3) / 2; iItem++) // 2014-3-10
                f_Element[st + iItem].length = f_Element[st + iItem + 1].start - f_Element[st + iItem].start;

            f_Element[st + (iObj - 1) / 2].length = length - f_Element[st + (iObj - 1) / 2].start;

            for (iItem = 0; iItem <= (iObj - 1) / 2; iItem++) {
                f_Element[st + iItem].start += start;
                f_Element[st + iItem].end = f_Element[st + iItem].start + f_Element[st + iItem].length - 1;
            }

            return 1; // 存在双峰，但只算一个气体
            // return (iObj+1)/2;
        }
    }

    void DBaseLine(double f_baseline[], double f_origData[], int count[], int wsize[], int length, double thr[]) {
        // 用于记录轮廓点出现次数
        int iItem, iObj;
        int num[] = new int[length];
        double f_dif[] = new double[length];
        double tmp;

        // 记录谱线首尾两端点
        num[0] = 1;
        num[length - 1] = 1;

        f_baseline[0] = f_origData[0];
        f_baseline[length - 1] = f_origData[length - 1];

        for (iItem = 1; iItem <= length - 1; iItem++) {
            if (iItem >= 15000)
                break;

            f_dif[iItem] = f_origData[iItem] - f_origData[iItem - 1];

            if (0 != count[iItem])
                f_dif[iItem] = f_dif[iItem] / count[iItem];
        }
        f_dif[0] = f_dif[1];

        // 寻找窗内最小值作为轮廓，并记录该值位置及出现次数
        for (iItem = 0; iItem <= length - 2; iItem++) {
            int j = iItem;
            tmp = f_origData[j];

            for (int k = iItem + 1; k <= wsize[iItem]; k++) {
                if (tmp >= f_origData[k]) {
                    j = k;
                    tmp = f_origData[j];
                }
            }

            f_baseline[j] = tmp;
            num[j]++;
        }

        // 剔除无效轮廓点
        // double dtmp = 0.0;
        // int dcnt = 0;
        for (iItem = 0; iItem <= length - 2; iItem++) {
            if (num[iItem] > 0) {
                iObj = iItem + 1;
                int cnt = count[iItem];

                if (f_dif[iObj] * f_dif[iObj - 1] > 0)
                    cnt += count[iObj];
                else
                    cnt = count[iObj];

                double thr0, thr1;
                if (iObj < length / 3)
                    thr0 = thr[0];
                else if (iObj < length * 2 / 3)
                    thr0 = thr[1];
                else
                    thr0 = thr[2];

                tmp = f_dif[iObj] > 0 ? f_dif[iObj] : -f_dif[iObj];
                thr1 = iItem + 500 * 2;
                thr1 = thr1 > length ? length : thr1;
                while ((num[iObj] == 0 || tmp >= thr0 || (f_dif[iObj] < 0 && cnt <= 25)) && iObj <= thr1 - 2) {
                    if (num[iObj] >= 40)
                        break;

                    num[iObj] = 0;
                    iObj++;

                    tmp = f_dif[iObj] > 0 ? f_dif[iObj] : -f_dif[iObj];
                    if (f_dif[iObj] * f_dif[iObj - 1] > 0)
                        cnt += count[iObj];
                    else
                        cnt = count[iObj];
                }

                num[iItem] = iObj;
            }
        }
        num[length - 1] = length - 1;

        // 线性插值，补足完整的轮廓线
        for (iItem = 0; iItem <= length - 2; iItem++) {
            if (num[iItem] > 0) {
                double iK = 0.0;
                int op = iItem;
                int ed = num[iItem];
                if (ed > op)
                    iK = (f_origData[ed] - f_origData[op]) / (ed - op);
                for (int j = op; j <= ed; j++) {
                    f_baseline[j] = f_origData[op] + iK * (j - op);
                    f_baseline[j] = (int) (f_baseline[j] + 0.5);
                    if (f_origData[j] - f_baseline[j] <= 25)
                        f_baseline[j] = f_origData[j];
                }
            }
        }
        int i = 0;
    }

    int DPeakSplit(SNPeak f_Peak[], double f_newData[], int count[], int length, List<Oilconfig> ol, SNElement f_elem[],
            SYN_Device pDevice) {
        int iItem;
        int iBegin = 0;
        int iGas = 0;
        List<Double> sss = new ArrayList<>();// 谷高度
        double max[] = new double[7];
        double min[] = new double[7];
        int maxlo[] = new int[7];
        int minlo[] = new int[7];
        boolean iscomplete[] = new boolean[7];

        for (iItem = 1; iItem <= length - 1; iItem++) {
            if (f_newData[iItem] > 0 && f_newData[iItem - 1] > 0) // 持续
            {
                for (int i = 0; i < 7; i++) {
                    if (iItem > ol.get(i).getStart() && iItem < ol.get(i).getEnd()) {
                        double maxvalue = calMax2(f_newData, iItem, 1);
                        if (maxvalue > 0) {
                            if (iscomplete[i] == true && maxvalue > max[i]) {
                                iscomplete[i] = false;
                                maxlo[i] = iItem;
                            }
                            max[i] = Max(max[i], maxvalue);
                            if (maxvalue > max[i]) {
                                iscomplete[i] = false;
                                maxlo[i] = iItem;
                            } else if (maxlo[i] == 0) {
                                maxlo[i] = iItem;
                            }
                        }
                        double minvalue = calMin2(f_newData, iItem, 1);
                        if (minvalue > 0) {
                            if (min[i] == 0) {
                                min[i] = minvalue;
                            } else {
                                min[i] = Min(min[i], minvalue);
                            }
                            minlo[i] = iItem;
                        }
                        if (minvalue != 0) {
                            sss.add(minvalue);
                        }
                    }
                }
            } else if (f_newData[iItem] > 0 && f_newData[iItem - 1] == 0) // 开始
            {
                iBegin = iItem;
            } else if (f_newData[iItem] == 0 && f_newData[iItem - 1] > 0) // 结束
            {
                for (int i = 0; i < 7; i++) {
                    if (maxlo[i] > ol.get(i).getStart() && maxlo[i] < ol.get(i).getEnd() && !iscomplete[i]) {
                        f_elem[i].id = i;
                        f_elem[i].location = maxlo[i];
                        f_elem[i].height = max[i];
                        if ((i + 1) < 7 && maxlo[i + 1] > iBegin && maxlo[i + 1] < iItem) {// 有双峰
                            // 第一峰
                            f_elem[i].start = iBegin;
                            if (minlo[i] == 0) {
                                f_elem[i].end = minlo[i + 1];
                            } else {
                                f_elem[i].end = minlo[i];
                            }
                            f_elem[i].length = f_elem[i].end - f_elem[i].start + 1;
                            iscomplete[i] = true;
                            f_elem[i].area = DArea0(f_newData, f_elem[i].start, f_elem[i].length);// 最后再算面积

                            i++;
                            // 第二峰
                            f_elem[i].id = i;
                            f_elem[i].location = maxlo[i];
                            f_elem[i].height = max[i];
                            if (minlo[i - 1] == 0) {
                                f_elem[i].start = minlo[i];
                            } else {
                                f_elem[i].start = minlo[i - 1];
                            }
                            f_elem[i].end = iItem;
                            f_elem[i].length = f_elem[i].end - f_elem[i].start + 1;
                            iscomplete[i] = true;
                            f_elem[i].area = DArea0(f_newData, f_elem[i].start, f_elem[i].length);
                        } else {
                            f_elem[i].start = iBegin;
                            f_elem[i].end = iItem;
                            f_elem[i].length = f_elem[i].end - f_elem[i].start + 1;
                            iscomplete[i] = true;
                            f_elem[i].area = DArea0(f_newData, f_elem[i].start, f_elem[i].length);
                        }
                    }
                }
            }
        }
        return iGas;
    }

    private void updatePdevice(SYN_Device pDevice, SNElement[] f_elem, int i) {
        double height = f_elem[i].height / 1000.0;
        double fScale = 0;
        if (height < pDevice.pGas[i].pPara[0].fPeakHeight)// 低浓度
        {
            fScale = pDevice.pGas[i].pPara[0].fScale;
        } else if (height >= pDevice.pGas[i].pPara[0].fPeakHeight
                && height < pDevice.pGas[i].pPara[1].fPeakHeight)// 中浓度
        {
            fScale = pDevice.pGas[i].pPara[1].fScale;
        } else {
            fScale = pDevice.pGas[i].pPara[2].fScale;
        }
        pDevice.pGas[i].fPeakPos = f_elem[i].location;
        pDevice.pGas[i].fDensity = height * fScale;// 浓度 = 峰高 * 因子系数
        pDevice.pGas[i].fPeakArea = f_elem[i].area / 100000.0;
        pDevice.pGas[i].iVarType = i;
        pDevice.iDevStr += i;
        pDevice.iDevStr += ",";
        pDevice.iDevStr += gasstr[i];
        pDevice.iDevStr += ",";
        pDevice.iDevStr += f_elem[i].location;
        pDevice.iDevStr += ",";
        pDevice.iDevStr += f_elem[i].height;
        pDevice.iDevStr += ",";
        double area = f_elem[i].area / 100000.0d;
        String rate = new DecimalFormat("0.##########").format(area);
        pDevice.iDevStr += rate;
        pDevice.iDevStr += ",";
        pDevice.iDevStr += height * fScale;
        pDevice.iDevStr += "|";
    }

    private double Max(double d, double calMax2) {
        return d > calMax2 ? d : calMax2;
    }

    private double Min(double d, double calMax2) {
        return d < calMax2 ? d : calMax2;
    }

    // 递归法取极大值
    public double calMax2(double f_newData[], int iItem, int offset) {
        if ((f_newData[iItem] == f_newData[iItem - offset] || f_newData[iItem] == f_newData[iItem + offset])
                && f_newData[iItem - offset] != 0 && f_newData[iItem + offset] != 0 && offset < 20) {
            return calMax2(f_newData, iItem, ++offset);
        }
        if (f_newData[iItem] > f_newData[iItem - offset] && f_newData[iItem] > f_newData[iItem + offset]) {
            if ((f_newData[iItem + 5 + offset] - f_newData[iItem]) < 0) {
                return f_newData[iItem];
            }
        }
        return 0;
    }

    // 递归法取极小值
    public double calMin2(double f_newData[], int iItem, int offset) {
        if ((f_newData[iItem] == f_newData[iItem - offset] || f_newData[iItem] == f_newData[iItem + offset])
                && f_newData[iItem - offset] != 0 && f_newData[iItem + offset] != 0 && offset < 20) {
            return calMin2(f_newData, iItem, ++offset);
        }
        if (f_newData[iItem] < f_newData[iItem - offset] && f_newData[iItem] < f_newData[iItem + offset]) {
            if ((f_newData[iItem + 10 + offset] - f_newData[iItem]) > 0) {
                return f_newData[iItem];
            }
        }
        return 0;
    }

    class SNPeak {
        int count;
        int length;
        int start;
    }

    class SNElement {
        int id; // 所在谱峰ID
        int start; // 开始位置
        int end; // 结束位置
        int length; // 持续长度
        int location; // 峰顶位置

        int temp; // 温度
        double pa; // 大气压强
        double factor; // 校正因子
        double height; // 峰高
        double area; // 峰面积
        double density; // 浓度
    }

    // 计算基线提取算法的相关差分阈值
    double DAdaptThreshold(double f_origData[], int start, int length, int count[], double fac) {
        int cnt = 0, iItem;
        int nbin = 100;
        double dThr = 200;
        double tmp = 0.0;
        int hist[] = new int[100];
        double f_dif[] = new double[5000];
        // 计算差分绝对值
        cnt = count[0];
        for (iItem = 1; iItem <= length - 1; iItem++) {
            f_dif[iItem] = f_origData[start + iItem] - f_origData[start + iItem - 1];
            if (f_dif[iItem] <= -dThr || f_dif[iItem] >= dThr)
                f_dif[iItem] = dThr - 1.0;
            else if (f_dif[iItem] < 0)
                f_dif[iItem] = -f_dif[iItem];
            f_dif[iItem] = f_dif[iItem] / count[start + iItem];
            if (tmp < f_dif[iItem])
                tmp = f_dif[iItem];
            cnt += count[start + iItem];
        }
        f_dif[0] = f_dif[1];
        tmp = (tmp + 1.0) / nbin;
        fac = fac * cnt;
        f_dif[0] = f_dif[1];
        // 计算直方图，确定阈值
        for (iItem = 0; iItem <= length - 1; iItem++)
            hist[(int) (f_dif[iItem] / tmp)] += count[start + iItem];

        for (iItem = 1; iItem <= nbin - 1; iItem++)
            hist[iItem] += hist[iItem - 1];
        cnt = 0;
        while (hist[cnt] <= fac && cnt < nbin - 1) {
            cnt++;
        }
        tmp = (cnt + 0.5) * tmp;
        if (tmp < 1)
            tmp = 1.0;
        return (tmp);
    }

    // 调整色谱数据压缩后对应的窗长
    void DWindowSize(int winSize[], int count[], int length, int wsize) {
        int i, iObj;
        int buf[] = new int[15000];
        buf[0] = count[0];
        for (i = 1; i <= length - 1; i++)
            buf[i] = buf[i - 1] + count[i];
        for (i = 0; i <= length - 2; i++) {
            iObj = i + 1;
            while (buf[iObj] - buf[i] < wsize && iObj <= length - 2)
                iObj++;
            winSize[i] = iObj;
        }
        winSize[length - 1] = length - 1;
        buf[length - 1] = count[length - 1];
        for (i = length - 2; i >= 0; i--)
            buf[i] = buf[i + 1] + count[i];
        winSize[length] = 0;
    }

    // 对油色谱原始数据进行压缩
    int DDataCompact(double f_Data[], int count[], double f_origData[], int length) {
        int cnt = 0;
        count[0] = 1;
        f_Data[0] = f_origData[0];
        for (int iItem = 1; iItem <= length - 1; iItem++) {
            if (f_origData[iItem] == f_origData[iItem - 1]) {
                count[cnt]++;
            } else {
                cnt++;
                count[cnt] = 1;
                f_Data[cnt] = f_origData[iItem];
            }
        }
        return (cnt + 1);
    }

    // 数据还原
    int DDataExpand(double f_newData[], double f_Data[], int count[], int length) {
        int num = 0;
        int iItem, iObj;

        for (iItem = 0; iItem <= length - 1; iItem++)
            num += count[iItem];

        int cnt = num;
        for (iItem = length - 1; iItem >= 0; iItem--) {
            for (iObj = 0; iObj <= count[iItem] - 1; iObj++)
                f_newData[--cnt] = f_Data[iItem];
        }
        return num;
    }

    // 平滑滤波
    void DFilter(double f_newData[], double f_origData[], int length, int nk) {
        int iItem, iObj;
        int iNum = nk / 2;
        double tmp;
        for (iItem = 0; iItem <= iNum - 1; iItem++) {
            tmp = 0;
            for (iObj = 0; iObj <= iItem + iNum; iObj++)
                tmp += f_origData[iObj];
            f_newData[iItem] = tmp / (iItem + iNum + 1);
        }
        for (iItem = iNum; iItem <= length - iNum - 1; iItem++) {
            tmp = 0;
            for (iObj = iItem - iNum; iObj <= iItem + iNum; iObj++)
                tmp += f_origData[iObj];
            f_newData[iItem] = tmp / nk;
        }
        for (iItem = length - iNum; iItem <= length - 1; iItem++) {
            tmp = 0;
            for (iObj = iItem - iNum; iObj <= length - 1; iObj++)
                tmp += f_origData[iObj];
            f_newData[iItem] = tmp / (length - iItem + iNum);
        }
    }

    private void CMD_DATA(String str, byte[] bt, Integer addrint) {
        simulatestr = new StringBuilder();
        wpk = new StringBuilder();
        wBKPara[addrint] = parseHex4(str.substring(10, 14));// 获取包数量
        wdev.put(addrint, new ArrayList<>());
        wStatus[addrint] = CMD_RECORD;// 开始采样
        delFile(System.getProperty("user.dir") + "\\11.txt");
        // 判断是否需要标定
        Example example = new Example(Oilconfig.class);
        Example.Criteria criteria = example.createCriteria();
        if (ad.getStationid() != null) {
            criteria.andEqualTo("stationid", ad.getStationid());
        }
        if (ad.getDevicegroup() != null) {
            criteria.andEqualTo("devicegroup", ad.getDevicegroup());
        }
        if (addrint != null) {
            criteria.andEqualTo("deviceaddr", addrint);
        }
        List<Oilconfig> ol = oilconfigmapper.selectByExample(example);
        if (ol == null || ol.size() == 0) {
            setText("" + languageManager.getLan().getAddress() + "<" + addrint + ">"
                    + languageManager.getLan().getConfigurationInformationMissing() + "！！");
            return;
        }
        // H2,CO,CH4,CO2,C2H4,C2H6,C2H2
        f_H2 = ol.get(0).getOilstandard();
        f_CO = ol.get(1).getOilstandard();
        f_CH4 = ol.get(2).getOilstandard();
        f_CO2 = ol.get(3).getOilstandard();
        f_C2H4 = ol.get(4).getOilstandard();
        f_C2H6 = ol.get(5).getOilstandard();
        f_C2H2 = ol.get(6).getOilstandard();
        if (f_H2 == 0 && f_CO == 0 && f_CH4 == 0 && f_CO2 == 0 && f_C2H4 == 0 && f_C2H6 == 0 && f_C2H2 == 0) {// 未标定
            isoilstand = false;
            updateSimulate(0, addrint);
            return;
        }
        if (f_H2 != 0 && f_CO != 0 && f_CH4 != 0 && f_CO2 != 0 && f_C2H4 != 0 && f_C2H6 != 0 && f_C2H2 != 0) {// 7组分
            isoilstand = true;
            updateSimulate(1, addrint);
            return;
        }
        if (f_H2 != 0 && f_CO != 0 && f_CH4 != 0 && f_CO2 != 0 && f_C2H4 == 0 && f_C2H6 != 0 && f_C2H2 == 0) {// 无C2H2,C2H4
            isoilstand = true;
            updateSimulate(2, addrint);
            return;
        }
        if (f_H2 != 0 && f_CO != 0 && f_CH4 != 0 && f_CO2 != 0 && f_C2H4 != 0 && f_C2H6 != 0 && f_C2H2 == 0) {// 无C2H2
            isoilstand = true;
            updateSimulate(3, addrint);
            return;
        }
        if (f_H2 != 0 && f_CO != 0 && f_CH4 != 0 && f_CO2 != 0 && f_C2H4 == 0 && f_C2H6 == 0 && f_C2H2 == 0) {// 无C2H2,C2H4,C2H6
            isoilstand = true;
            updateSimulate(4, addrint);
            return;
        }
        if (f_H2 != 0 && f_CO != 0 && f_CH4 != 0 && f_CO2 != 0 && f_C2H4 != 0 && f_C2H6 == 0 && f_C2H2 == 0) {// 无C2H4,C2H6
            isoilstand = true;
            updateSimulate(5, addrint);
            return;
        }
        if (f_H2 != 0 && f_CO != 0 && f_CH4 != 0 && f_CO2 != 0 && f_C2H4 == 0 && f_C2H6 != 0 && f_C2H2 != 0) {// 无C2H4
            isoilstand = true;
            updateSimulate(6, addrint);
            return;
        }
        if (f_H2 != 0 && f_CO == 0 && f_CH4 != 0 && f_CO2 != 0 && f_C2H4 == 0 && f_C2H6 == 0 && f_C2H2 == 0) {// 无CO,C2H2,C2H4,C2H6
            isoilstand = true;
            updateSimulate(7, addrint);
            return;
        }
        if (f_H2 != 0 && f_CO != 0 && f_CH4 == 0 && f_CO2 != 0 && f_C2H4 == 0 && f_C2H6 == 0 && f_C2H2 == 0) {// 只有H2,CO,CO2
            isoilstand = true;
            updateSimulate(8, addrint);
            return;
        }
        if (f_H2 != 0 && f_CO == 0 && f_CH4 == 0 && f_CO2 != 0 && f_C2H4 == 0 && f_C2H6 == 0 && f_C2H2 == 0) {// 只有H2,CO2
            isoilstand = true;
            updateSimulate(9, addrint);
            return;
        }
        if (f_H2 != 0 && f_CO == 0 && f_CH4 != 0 && f_CO2 != 0 && f_C2H4 == 0 && f_C2H6 == 0 && f_C2H2 == 0) {// 只有H2,CH4,CO2
            isoilstand = true;
            updateSimulate(10, addrint);
            return;
        }
        updateSimulate(1, addrint);// 剩余情况七组分
        isoilstand = true;
    }

    private void updateSimulate(Integer i, Integer addrint) {
        Oilsensor os = new Oilsensor();
        os.setStationid(ad.getStationid());
        os.setDevicegroup(ad.getDevicegroup());
        os.setDeviceaddr(addrint);
        os.setSimulate(i);
        oilserviceimpl.Update(os, false);
    }

    private void CMD_HEART(String str, byte[] bt, Integer addrint) {

        if ((0xFF & bt[6]) > 0x80) {
            wStatus[addrint] = CMD_DATA;// 读取包数量和长度
        } else {
            wStatus[addrint] = CMD_MST;// 读取微水、环境
        }
    }

    private void CMD_MST(String str, byte[] bt, Integer addrint) {

        int i = 0;
        BigDecimal Pressure = IEEE754Utils.strbytesToSingle(str.substring(10 + i * 8, 18 + i++ * 8));
        BigDecimal Temperature = IEEE754Utils.strbytesToSingle(str.substring(10 + i * 8, 18 + i++ * 8));
        BigDecimal TemperatureCtrl1 = IEEE754Utils.strbytesToSingle(str.substring(10 + i * 8, 18 + i++ * 8));
        BigDecimal TemperatureCtrl2 = IEEE754Utils.strbytesToSingle(str.substring(10 + i * 8, 18 + i++ * 8));
        BigDecimal GasContent = IEEE754Utils.strbytesToSingle(str.substring(10 + i * 8, 18 + i++ * 8));
        BigDecimal H2O = IEEE754Utils.strbytesToSingle(str.substring(10 + i * 8, 18 + i++ * 8));
        Oilsensor os = new Oilsensor();
        os.setStationid(ad.getStationid());
        os.setDevicegroup(ad.getDevicegroup());
        os.setDeviceaddr(addrint);
        os.setLastpressure(Pressure.floatValue());
        os.setLasttemperature(Temperature.floatValue());
        os.setLasttemperaturectrl1(TemperatureCtrl1.floatValue());
        os.setLasttemperaturectrl2(TemperatureCtrl2.floatValue());
        os.setLastgascontent(GasContent.floatValue());

        Example example = new Example(Oilconfig.class);
        Example.Criteria criteria = example.createCriteria();
        if (ad.getStationid() != null) {
            criteria.andEqualTo("stationid", ad.getStationid());
        }
        if (ad.getDevicegroup() != null) {
            criteria.andEqualTo("devicegroup", ad.getDevicegroup());
        }
        if (addrint != null) {
            criteria.andEqualTo("deviceaddr", addrint);
        }
        float h2obasevalue = 21.6f;
        List<Oilconfig> ol = oilconfigmapper.selectByExample(example);
        if (ol == null || ol.size() == 0) {
            setText("" + languageManager.getLan().getAddress() + "<" + addrint + ">"
                    + languageManager.getLan().getConfigurationInformationMissing() + "！！");
        } else {
            if (ol.get(9).getOilstandard() != null) {
                h2obasevalue = ol.get(9).getOilstandard();
            }
        }
        float H2O1 = h2obasevalue * ((float) Math.random() * 2 + 9) / 10;
        os.setLasth2o(H2O1);
        os.setLastppm(H2O1);
        oilserviceimpl.Update(os, false);
        wStatus[addrint] = CMD_HEART;
        addridx++;
    }

    // 读取别人油色谱转发
    private void recvOilDf(String str) {
        str = str.toUpperCase();
        setText(str);
        String addrstr = str.substring(0, 2);
        Integer addrint = parseHex4(addrstr);
        Oilsensor Oilsensor = new Oilsensor();
        Oilsensor.setLastcommunicationstatus(0);
        Oilsensor.setStationid(ad.getStationid());
        Oilsensor.setDevicegroup(ad.getDevicegroup());
        if (oilserviceimpl.Update(Oilsensor, false) == 0) {
            // logger.info("数据更新失败！请检查原因...");
        }
        reSend[0] = 0;
        String[] addrarray = ad.getSubswitch().split(",");
        String ustr = str.substring(6);
        addrint = Integer.parseInt(addrarray[0]);
        int singlelen = 44;
        for (int i = 0; i < (ustr.length() - 4) / singlelen; i++) {
            String cstr = ustr.substring(singlelen * i, singlelen * (i + 1));
            Oilsensor target = new Oilsensor();
            target.setStationid(ad.getStationid());
            target.setDevicegroup(ad.getDevicegroup());
            target.setDeviceaddr(i + addrint);
            Oilsensor trans = oilserviceimpl.getModel(target);
            Float H2 = parseHex4(cstr.substring(0, 4)) / 10f;
            Float CO = parseHex4(cstr.substring(4, 8)) / 10f;
            Float CH4 = parseHex4(cstr.substring(8, 12)) / 10f;
            Float CO2 = parseHex4(cstr.substring(12, 16)) / 10f;
            Float C2H4 = parseHex4(cstr.substring(16, 20)) / 10f;
            Float C2H2 = parseHex4(cstr.substring(20, 24)) / 10f;
            Float C2H6 = parseHex4(cstr.substring(24, 28)) / 10f;
            Float O2 = parseHex4(cstr.substring(28, 32)) / 10f;
            Float N2 = parseHex4(cstr.substring(32, 36)) / 10f;
            Float TotHyd = parseHex4(cstr.substring(36, 40)) / 10f;
            Float PPM = parseHex4(cstr.substring(40, 44)) / 10f;
            if (trans == null) {
                setText("当前数据库无监测点：" + (i + addrint) + " ！"
                        + languageManager.getLan().getPleaseAddMonitoringPointFirst() + "！");
                return;
            }
            String memo = H2.toString() + "," + CO.toString() + "," + CH4.toString() + "," + CO2.toString() + ","
                    + C2H4.toString() + "," + C2H2.toString() + "," + C2H6.toString() + "," + TotHyd.toString() + ","
                    + PPM.toString() + ",";
            if (trans.getMemo().equals(memo)) {
                continue;
            }
            target.setLasth2(H2);
            target.setLastco(CO);
            target.setLastch4(CH4);
            target.setLastco2(CO2);
            target.setLastc2h4(C2H4);
            target.setLastc2h2(C2H2);
            target.setLastc2h6(C2H6);
            target.setLasttothyd(TotHyd);
            target.setLastppm(PPM);
            target.setLasth2o(PPM);
            target.setLasto2(O2);
            target.setLastn2(N2);
            target.setDeviceaddr(i + addrint);
            target.setStationid(ad.getStationid());
            target.setDevicegroup(ad.getDevicegroup());
            target.setLastcommunicationstatus(0);
            target.setLastdatatime(new Date());
            target.setMemo(memo);
            UpdateAndAdd(trans, target, false, 0);
        }
    }

    // 直连自己的油色谱
    private void requestDir(Appdevice Appdevice) throws InterruptedException {
        allowDisplay = false;
        issend.put(Thread.currentThread().getId(), true);
        int timeoutsp = (int) Math.round(Appdevice.getTimeoutsp() * 1000);
        timersp = (int) Math.round(Appdevice.getTimersp() * 1000);
        int timersptemp = timersp;
        String[] addrarray = Appdevice.getSubswitch().split(",");
        // dataTransform(50, false);
        while (issend.get(Thread.currentThread().getId()) != null) {
            if (addridx >= addrarray.length)
                addridx = 0;
            int addrindex = Integer.parseInt(addrarray[addridx]);
            if ((System.currentTimeMillis() - lasttime) < 30000) {
                Thread.sleep(1000);
                continue;
            }
            rlock.lock();
            try {
                if (isrun) {

                    if (wStatus[addrindex] == 0)
                        wStatus[addrindex] = CMD_HEART;
                    switch (wStatus[addrindex]) {
                        case CMD_HEART:
                            timersp = timersptemp;
                            break;
                        case CMD_MST:
                            timersp = timersptemp;
                            break;
                        case CMD_RECORD:
                            timersp = 1000;
                            break;
                    }
                    Send(CreateCommand(addrindex, wStatus[addrindex], null, null, null, null, null, null, null, null,
                            null, null, null,
                            true));
                    sendCondition.await(timeoutsp, TimeUnit.MILLISECONDS);
                    reSend[addrindex]++;
                    if (reSend[addrindex] > 3) {
                        wStatus[addrindex] = CMD_HEART;
                        oilserviceimpl.UpdateStatus(ad, addrindex, 1);
                        reSend[addrindex] = 0;
                        addridx++;

                    }
                } else if (rescode != 0) {
                    setText(resmsg[rescode]);
                }
            } catch (Exception e) {
                // TODO: handle exception
            } finally {
                rlock.unlock();
            }
        }
    }

    public String CreateCommand(Integer addrindex, Integer status, Integer count, Integer hours1, Integer minutes1,
            Integer hours2, Integer minutes2, Integer hours3, Integer minutes3, Integer hours4, Integer minutes4,
            Integer targetaddr, Integer targetpoint, boolean display) {
        String byHead = "7E";
        String byDirAddr = String.format("%02X", addrindex);
        String bySrcAddr = "00";
        String byLen = "02";
        String packId = "0000";// 包序号
        String byEnd = "0F";
        if (CMD_RECORD == status) {
            byLen = "02";
            packId = String.format("%04X", wBKNum[addrindex]);// 包序号
        }
        if (CMD_WSAMPLE == status) {
            if (count == 1) {
                byLen = "03";// 长度
                packId = String.format("%02X", 1);// 采样次数
                packId += String.format("%02X", hours1);
                packId += String.format("%02X", minutes1);
            } else if (count == 2) {
                byLen = "05";
                packId = String.format("%02X", 2);
                packId += String.format("%02X", hours1);
                packId += String.format("%02X", minutes1);
                packId += String.format("%02X", hours2);
                packId += String.format("%02X", minutes2);
            } else if (count == 3) {
                byLen = "07";
                packId = String.format("%02X", 3);
                packId += String.format("%02X", hours1);
                packId += String.format("%02X", minutes1);
                packId += String.format("%02X", hours2);
                packId += String.format("%02X", minutes2);
                packId += String.format("%02X", hours3);
                packId += String.format("%02X", minutes3);
            } else if (count == 4) {
                byLen = "09";
                packId = String.format("%02X", 4);
                packId += String.format("%02X", hours1);
                packId += String.format("%02X", minutes1);
                packId += String.format("%02X", hours2);
                packId += String.format("%02X", minutes2);
                packId += String.format("%02X", hours3);
                packId += String.format("%02X", minutes3);
                packId += String.format("%02X", hours4);
                packId += String.format("%02X", minutes4);
            }
        }
        if (CMD_RADDR == status) {// 读地址
            byDirAddr = "FF";
        }
        if (CMD_WADDR == status) {
            packId = String.format("%02X", targetaddr) + "00";
        }
        if (CMD_WSAMPLENumber == status) {
            byLen = "04";
            packId = String.format("%08X", targetpoint);
        }
        if (CMD_GETTIME == status) {
            byLen = "02";
            packId = "0000";
        }
        if (CMD_SETTIME == status) {
            byLen = "07";
            TimeZone defaultTimeZone = TimeZone.getDefault();
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeZone(defaultTimeZone);
            Date sourceDate = calendar.getTime();
            SimpleDateFormat sbf = new SimpleDateFormat("ssmmHH00ddMMyyyy");
            String dts = sbf.format(sourceDate);
            packId = dts.substring(0, 12) + dts.substring(14, 16);
        }
        String pSFrame = byDirAddr + bySrcAddr + String.format("%02X", status) + byLen + packId;
        byte[] bdata = hexStringToBytes(pSFrame);
        String crc = String.format("%02X", CRC8_MAXIM(bdata, 0, bdata.length));
        pSFrame = byHead + pSFrame;
        pSFrame += crc;
        pSFrame += byEnd;
        if (display)
            setText(" <" + languageManager.getLan().getAddress() + "：" + addrindex + ""
                    + languageManager.getLan().getCommand()
                    + ":" + status
                    + ">... " + languageManager.getLan().getInspection() + "......." + pSFrame);
        return pSFrame;
    }

    /**
     * 遥控命令,只需要构造发送报文带入参数
     * 
     * @param cstr
     */
    public void ControlCommand(String cstr) {
        controllerCmd = cstr;
        try {
            lasttime = System.currentTimeMillis();
            Thread.sleep(1000);
            rlock.lock();

            sendCondition.signal();
            Send(controllerCmd);
            setText(" <" + languageManager.getLan().getRemoteControlCommand() + ":"
                    + Integer.parseInt(cstr.substring(6, 8), 16)
                    + ">... "
                    + languageManager.getLan().getInspection() + "......." + cstr);
            Thread.sleep(2000);
            controllerCmd = "";// 发送完成以后清空发送命令
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            sendCondition.signal();
            rlock.unlock();
        }
    }

    // 读取别人油色谱的转发
    private void requestDf(Appdevice Appdevice) throws Exception {
        checkType = "crc16";
        issend.put(Thread.currentThread().getId(), true);
        String cstr = "";
        String[] addrarray = Appdevice.getSubswitch().split(",");
        while (issend.get(Thread.currentThread().getId()) != null) {
            for (String addrstr : addrarray) {
                int addrindex = Integer.parseInt(addrstr);
                rlock.lock();
                try {
                    if (isrun) {
                        if (addrindex > (Appdevice.getAddrmax() - Appdevice.getAddrmin() + 1))
                            addrindex = 1;
                        cstr = String.format(Appdevice.getCmd(), df.format(addrindex));
                        cstr = cstr + CRC16.calcCrc16(cstr);
                        Send(cstr);
                        sendCondition.await(timeoutsp, TimeUnit.MILLISECONDS);
                        reSend[0]++;
                        if (reSend[0] > 3) {
                            Oilsensor Oilsensor = new Oilsensor();
                            Oilsensor.setLastcommunicationstatus(1);
                            Oilsensor.setStationid(ad.getStationid());
                            Oilsensor.setDevicegroup(ad.getDevicegroup());
                            if (oilserviceimpl.Update(Oilsensor, false) == 0) {
                                // logger.info("数据更新失败！请检查原因...");
                            }
                            reSend[0] = 0;
                            addrindex++;
                        }
                    } else if (rescode != 0) {
                        setText(resmsg[rescode]);
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                } finally {
                    rlock.unlock();
                }
            }
        }
    }

    // 读取别人油色谱的61850
    private void read61850(String str) {
        Oilsensor currrecord = new Oilsensor();
        currrecord.setStationid(ad.getStationid());
        currrecord.setDevicegroup(ad.getDevicegroup());
        List<Oilsensor> lastrecordlist = oilserviceimpl.getLists(currrecord);
        if (lastrecordlist.size() != 0) {
            if (lastrecordlist.get(0).getStyle61850() != null) {
                String[] style = lastrecordlist.get(0).getStyle61850().split(",");
                for (String s : style) {
                    map61850.put(s.split("\\|")[0], s.split("\\|")[1]);
                }
            }
        }
        for (Oilsensor lastrecord : lastrecordlist) {
            currrecord.setDeviceaddr(lastrecord.getDeviceaddr());
            String alm = "";
            try {
                currrecord.setLastch4(
                        read61850FloatValue(String.format(isnull(map61850.get("CH4ppm")), lastrecord.getDeviceaddr())));
                currrecord.setLastc2h6(read61850FloatValue(
                        String.format(isnull(map61850.get("C2H6ppm")), lastrecord.getDeviceaddr())));
                currrecord.setLastc2h4(read61850FloatValue(
                        String.format(isnull(map61850.get("C2H4ppm")), lastrecord.getDeviceaddr())));
                currrecord.setLastc2h2(read61850FloatValue(
                        String.format(isnull(map61850.get("C2H2ppm")), lastrecord.getDeviceaddr())));
                currrecord.setLastco(
                        read61850FloatValue(String.format(isnull(map61850.get("COppm")), lastrecord.getDeviceaddr())));
                currrecord.setLastco2(
                        read61850FloatValue(String.format(isnull(map61850.get("CO2ppm")), lastrecord.getDeviceaddr())));
                currrecord.setLasto2(
                        read61850FloatValue(String.format(isnull(map61850.get("O2ppm")), lastrecord.getDeviceaddr())));
                currrecord.setLastn2(
                        read61850FloatValue(String.format(isnull(map61850.get("N2ppm")), lastrecord.getDeviceaddr())));
                currrecord.setLasth2(
                        read61850FloatValue(String.format(isnull(map61850.get("H2ppm")), lastrecord.getDeviceaddr())));
                currrecord.setLasth2o(
                        read61850FloatValue(String.format(isnull(map61850.get("Mst")), lastrecord.getDeviceaddr())));
                currrecord.setLastppm(currrecord.getLasth2o());
                alm += read61850IntValue(
                        String.format(isnull(map61850.get("CH4Alm1")), lastrecord.getDeviceaddr())) == 1 ? "甲烷高报," : "";
                alm += read61850IntValue(
                        String.format(isnull(map61850.get("CH4Alm2")), lastrecord.getDeviceaddr())) == 1 ? "甲烷高高报,"
                                : "";
                alm += read61850IntValue(
                        String.format(isnull(map61850.get("C2H6Alm1")), lastrecord.getDeviceaddr())) == 1 ? "乙烷高报,"
                                : "";
                alm += read61850IntValue(
                        String.format(isnull(map61850.get("C2H6Alm2")), lastrecord.getDeviceaddr())) == 1 ? "乙烷高高报,"
                                : "";
                alm += read61850IntValue(
                        String.format(isnull(map61850.get("C2H4Alm1")), lastrecord.getDeviceaddr())) == 1 ? "乙烯高报,"
                                : "";
                alm += read61850IntValue(
                        String.format(isnull(map61850.get("C2H4Alm2")), lastrecord.getDeviceaddr())) == 1 ? "乙烯高高报,"
                                : "";
                alm += read61850IntValue(
                        String.format(isnull(map61850.get("C2H2Am1")), lastrecord.getDeviceaddr())) == 1 ? "乙炔高报," : "";
                alm += read61850IntValue(
                        String.format(isnull(map61850.get("C2H2Am2")), lastrecord.getDeviceaddr())) == 1 ? "乙炔高高报,"
                                : "";
                alm += read61850IntValue(String.format(isnull(map61850.get("COAlm1")), lastrecord.getDeviceaddr())) == 1
                        ? "一氧化碳高报,"
                        : "";
                alm += read61850IntValue(String.format(isnull(map61850.get("COAlm2")), lastrecord.getDeviceaddr())) == 1
                        ? "一氧化碳高高报,"
                        : "";
                alm += read61850IntValue(
                        String.format(isnull(map61850.get("CO2Alm1")), lastrecord.getDeviceaddr())) == 1 ? "二氧化碳高报,"
                                : "";
                alm += read61850IntValue(
                        String.format(isnull(map61850.get("CO2Alm2")), lastrecord.getDeviceaddr())) == 1 ? "二氧化碳高高报,"
                                : "";
                // alm += read61850IntValue(String.format(isnull(map61850.get("O2Alm1") ),
                // lastrecord.getDeviceaddr())) == 1 ? "氧气高报," : "";
                // alm += read61850IntValue(String.format(isnull(map61850.get("O2Alm2") ),
                // lastrecord.getDeviceaddr())) == 1 ? "氧气高高报," : "";
                // alm += read61850IntValue(String.format(isnull(map61850.get("N2Alm1") ),
                // lastrecord.getDeviceaddr())) == 1 ? "氮气高报," : "";
                // alm += read61850IntValue(String.format(isnull(map61850.get("N2Alm2") ),
                // lastrecord.getDeviceaddr())) == 1 ? "氮气高高报," : "";
                alm += read61850IntValue(String.format(isnull(map61850.get("H2Alm1")), lastrecord.getDeviceaddr())) == 1
                        ? "氢气高报,"
                        : "";
                alm += read61850IntValue(String.format(isnull(map61850.get("H2Alm2")), lastrecord.getDeviceaddr())) == 1
                        ? "氢气高高报,"
                        : "";
                alm += read61850IntValue(
                        String.format(isnull(map61850.get("MstAlm1")), lastrecord.getDeviceaddr())) == 1 ? "微水高报," : "";
                alm += read61850IntValue(
                        String.format(isnull(map61850.get("MstAlm2")), lastrecord.getDeviceaddr())) == 1 ? "微水高高报,"
                                : "";
                alm += read61850IntValue(
                        String.format(isnull(map61850.get("SupDevRun")), lastrecord.getDeviceaddr())) == 1 ? "运行异常,"
                                : "";
                currrecord.setLastcommunicationstatus(read61850IntValue(
                        String.format(isnull(map61850.get("MoDevConf")), lastrecord.getDeviceaddr())));
            } catch (SocketException e) {
                if (Close()) {// 主动关闭
                    oilserviceimpl.UpdateStatus(ad, 1);
                    ComRunner.netmap.remove(ad.getId());
                }
            } catch (Exception e) {
                setText("读取数据出错！" + e.toString());
            }

            if (alm.equals("")) {
                currrecord.setLastalarmlevel(0);
                currrecord.setLastalarmmessage(alm);
                GetNormalAlarm("油色谱" + lastrecord.getDeviceaddr(), lastrecord.getDevicegroup(),
                        lastrecord.getDeviceaddr(), 0,
                        lastrecord.getPointname(), "", false);
                setText("无报警");
            } else {
                currrecord.setLastalarmlevel(2);
                currrecord.setLastalarmmessage(alm);
                GetNormalAlarm("油色谱" + lastrecord.getDeviceaddr(), lastrecord.getDevicegroup(),
                        lastrecord.getDeviceaddr(), 0,
                        lastrecord.getPointname(), alm, true);
                setText(alm);
            }

            currrecord.setLastdatatime(new Date());
            oilserviceimpl.Update(currrecord, false);

            Oilhistory transhis = new Oilhistory();
            transhis.setStationid(currrecord.getStationid());
            transhis.setDevicegroup(currrecord.getDevicegroup());
            transhis.setDeviceaddr(currrecord.getDeviceaddr());
            transhis.setPointname(currrecord.getPointname());
            transhis.setH2(currrecord.getLasth2());
            transhis.setCo(currrecord.getLastco());
            transhis.setCh4(currrecord.getLastch4());
            transhis.setCo2(currrecord.getLastco2());
            transhis.setC2h4(currrecord.getLastc2h4());
            transhis.setC2h2(currrecord.getLastc2h2());
            transhis.setC2h6(currrecord.getLastc2h6());
            transhis.setTothyd(currrecord.getLasttothyd());
            if (currrecord.getLastppm() == null) {
                transhis.setPpm(currrecord.getLastppm());
            } else {
                transhis.setPpm(currrecord.getLastppm());
            }
            transhis.setO2(currrecord.getLasto2());
            transhis.setN2(currrecord.getLastn2());
            transhis.setDatatime(currrecord.getLastdatatime());
            transhis.setAlarmlevel(currrecord.getLastalarmlevel());
            transhis.setAlarmmessage(currrecord.getLastalarmmessage());
            transhis.setElem(currrecord.getLastelem());
            transhis.setProcesseddata(currrecord.getLastprocesseddata());
            transhis.setCommunicationstatus(currrecord.getLastcommunicationstatus());
            if (oilserviceimpl.Add(transhis) == 0) {
                setText("添加历史数据失败，请检查数据库连接");
            }

            StringBuilder str2 = new StringBuilder();
            str2.append("【设备返回数据：】");
            str2.append(" 站点地址：" + currrecord.getStationid());
            str2.append(" 设备地址：" + currrecord.getDeviceaddr() + "\r\n");
            str2.append(" 氢气：" + currrecord.getLasth2() + "\r\n");
            str2.append(" 一氧化碳：" + currrecord.getLastco() + "\r\n");
            str2.append(" 甲烷：" + currrecord.getLastch4() + "\r\n");
            str2.append(" 二氧化碳：" + currrecord.getLastco2() + "\r\n");
            str2.append(" 乙烯：" + currrecord.getLastc2h4() + "\r\n");
            str2.append(" 乙烷：" + currrecord.getLastc2h6() + "\r\n");
            str2.append(" 乙炔：" + currrecord.getLastc2h2() + "\r\n");
            str2.append(" 总烃：" + currrecord.getLasttothyd() + "\r\n");
            str2.append(" 微水：" + currrecord.getLastppm() + "\r\n");
            // str2.append(" 氧气：" + currrecord.getLasto2() + "\r\n");
            // str2.append(" 氮气：" + currrecord.getLastn2() + "\r\n");
            setText(str2.toString());
        }
    }

    // 读取别人油色谱的数据库
    private void readdatabase(Appdevice Appdevice) throws Exception {
        issend.put(Thread.currentThread().getId(), true);
        setText("正在打开油色谱转发...");
        int timersp = (int) Math.round(Appdevice.getTimersp() * 1000);
        while (issend.get(Thread.currentThread().getId()) != null) {
            List<TOLM_Var> list = new ArrayList<>();
            for (int i = Appdevice.getAddrmin(); i <= Appdevice.getAddrmax(); i++) {
                TOLM_Var tv = new TOLM_Var();
                tv.setLdevid(i);
                list = tolm_varmapper.selectbytotal(tv);
                if (list == null || list.size() == 0) {
                    setText("本地数据库与远程数据库：" + i + " 对应不上！");
                    continue;
                }
                StringBuilder str2 = new StringBuilder();
                Float H2 = Float.parseFloat(list.get(0).getFvalue().toString());// 氢气
                Float CO = Float.parseFloat(list.get(1).getFvalue().toString());// 一氧化碳
                Float CH4 = Float.parseFloat(list.get(2).getFvalue().toString());// 甲烷
                Float CO2 = Float.parseFloat(list.get(3).getFvalue().toString());// 二氧化碳
                Float C2H4 = Float.parseFloat(list.get(4).getFvalue().toString());// 乙烯
                Float C2H2 = Float.parseFloat(list.get(5).getFvalue().toString());// 乙炔
                Float C2H6 = Float.parseFloat(list.get(6).getFvalue().toString());// 乙烷
                Float O2 = Float.parseFloat(list.get(7).getFvalue().toString());// 氧气
                Float N2 = Float.parseFloat(list.get(8).getFvalue().toString());// 氮气
                Float TotHyd = Float.parseFloat(list.get(9).getFvalue().toString());// 总径
                Float PPM = Float.parseFloat(list.get(15).getFvalue().toString());// 微水

                Oilsensor trans = new Oilsensor();
                trans.setStationid(ad.getStationid());
                trans.setDevicegroup(ad.getDevicegroup());
                trans.setDeviceaddr(i);
                trans = oilserviceimpl.getModel(trans);
                if (trans == null) {
                    setText("当前数据库无监测点：" + (i) + " ！ " + languageManager.getLan().getPleaseAddMonitoringPointFirst()
                            + "！");
                    return;
                }
                String memo = H2.toString() + "," + CO.toString() + "," + CH4.toString() + "," + CO2.toString() + ","
                        + C2H4.toString() + "," + C2H2.toString() + "," + C2H6.toString() + "," + TotHyd.toString()
                        + ","
                        + PPM.toString() + ",";
                if (trans.getMemo().equals(memo)) {
                    continue;
                }
                trans.setLasth2(H2);
                trans.setLastco(CO);
                trans.setLastch4(CH4);
                trans.setLastco2(CO2);
                trans.setLastc2h4(C2H4);
                trans.setLastc2h2(C2H2);
                trans.setLastc2h6(C2H6);
                trans.setLasttothyd(TotHyd);
                trans.setLastppm(PPM);
                // trans.setLasto2(O2);
                // trans.setLastn2(N2);
                trans.setDeviceaddr(i);
                trans.setStationid(1);
                trans.setDevicegroup(1);
                trans.setLastcommunicationstatus(0);
                trans.setLastdatatime(new Date());
                trans.setMemo(memo);
                String alarmMessage = "";// '报警消息
                int AlarmStatus[] = new int[11];
                if (trans.getH2warnvalue() == null || trans.getCowarnvalue() == null || trans.getCh4warnvalue() == null
                        || trans.getCo2warnvalue() == null || trans.getC2h4warnvalue() == null
                        || trans.getC2h2warnvalue() == null || trans.getC2h6warnvalue() == null
                        || trans.getTothydwarnvalue() == null || trans.getPpmalarmvalue() == null
                        || trans.getO2warnvalue() == null || trans.getN2alarmvalue() == null
                        || trans.getH2warnvalue() == null || trans.getCoalarmvalue() == null
                        || trans.getCh4alarmvalue() == null || trans.getCo2alarmvalue() == null
                        || trans.getC2h4alarmvalue() == null || trans.getC2h2alarmvalue() == null
                        || trans.getC2h6alarmvalue() == null || trans.getTothydalarmvalue() == null
                        || trans.getPpmalarmvalue() == null
                // || trans.getO2alarmvalue() == null
                // || trans.getN2alarmvalue() == null
                ) {
                    setText("当前监测点：" + (i) + " 未设置报警值！");
                    return;
                }

                AlarmStatus[0] = GetAlarmStatus(trans.getLasth2(), trans.getH2alarmvalue(),
                        trans.getH2alarmrelievevalue(),
                        trans.getH2warnvalue(), trans.getH2warnrelievevalue(), trans.getLasth2alarmstatus(), true);
                AlarmStatus[1] = GetAlarmStatus(trans.getLastco(), trans.getCoalarmvalue(),
                        trans.getCoalarmrelievevalue(),
                        trans.getCowarnvalue(), trans.getCowarnvalue(), trans.getLastcoalarmstatus(), true);
                AlarmStatus[2] = GetAlarmStatus(trans.getLastch4(), trans.getCh4alarmvalue(),
                        trans.getCh4alarmrelievevalue(),
                        trans.getCh4warnvalue(), trans.getCh4warnrelievevalue(), trans.getLastch4alarmstatus(), true);
                AlarmStatus[3] = GetAlarmStatus(trans.getLastco2(), trans.getCo2alarmvalue(),
                        trans.getCo2alarmrelievevalue(),
                        trans.getCo2warnvalue(), trans.getCo2warnrelievevalue(), trans.getLastco2alarmstatus(), true);
                AlarmStatus[4] = GetAlarmStatus(trans.getLastc2h4(), trans.getC2h4alarmvalue(),
                        trans.getC2h4alarmrelievevalue(),
                        trans.getC2h4warnvalue(), trans.getC2h4warnrelievevalue(), trans.getLastc2h4alarmstatus(),
                        true);
                AlarmStatus[5] = GetAlarmStatus(trans.getLastc2h2(), trans.getC2h2alarmvalue(),
                        trans.getC2h2alarmrelievevalue(),
                        trans.getC2h2warnvalue(), trans.getC2h2warnrelievevalue(), trans.getLastc2h2alarmstatus(),
                        true);
                AlarmStatus[6] = GetAlarmStatus(trans.getLastc2h6(), trans.getC2h6alarmvalue(),
                        trans.getC2h6alarmrelievevalue(),
                        trans.getC2h6warnvalue(), trans.getC2h6warnrelievevalue(), trans.getLastc2h6alarmstatus(),
                        true);
                AlarmStatus[7] = GetAlarmStatus(trans.getLasttothyd(), trans.getTothydalarmvalue(),
                        trans.getTothydalarmrelievevalue(),
                        trans.getTothydwarnvalue(), trans.getTothydwarnrelievevalue(), trans.getLasttothydalarmstatus(),
                        true);
                AlarmStatus[8] = GetAlarmStatus(trans.getLastppm(), trans.getPpmalarmvalue(),
                        trans.getPpmalarmrelievevalue(),
                        trans.getPpmwarnvalue(), trans.getPpmwarnrelievevalue(), trans.getLastppmalarmstatus(), true);
                // AlarmStatus[9] = GetAlarmStatus(trans.getLasto2(),
                // trans.getO2alarmvalue(),trans.getO2alarmrelievevalue(),
                // trans.getO2warnvalue(),
                // trans.getO2warnrelievevalue(),trans.getLasto2alarmstatus(), true);
                // AlarmStatus[10] = GetAlarmStatus(trans.getLastn2(),
                // trans.getN2alarmvalue(),trans.getN2alarmrelievevalue(),
                // trans.getN2warnvalue(),
                // trans.getN2warnrelievevalue(),trans.getLastn2alarmstatus(), true);
                // 报警消息
                alarmMessage += GetAlarmMessage(AlarmStatus[0], "氢气");
                alarmMessage += GetAlarmMessage(AlarmStatus[1], "一氧化碳");
                alarmMessage += GetAlarmMessage(AlarmStatus[2], "甲烷");
                alarmMessage += GetAlarmMessage(AlarmStatus[3], "二氧化碳");
                alarmMessage += GetAlarmMessage(AlarmStatus[4], "乙烯");
                alarmMessage += GetAlarmMessage(AlarmStatus[5], "乙炔");
                alarmMessage += GetAlarmMessage(AlarmStatus[6], "乙烷");
                alarmMessage += GetAlarmMessage(AlarmStatus[7], "总烃");
                alarmMessage += GetAlarmMessage(AlarmStatus[8], "微水");
                // alarmMessage += GetAlarmMessage(AlarmStatus[9], "氧气");
                // alarmMessage += GetAlarmMessage(AlarmStatus[10], "氮气");
                trans.setLasth2alarmstatus(AlarmStatus[0]);
                trans.setLastcoalarmstatus(AlarmStatus[1]);
                trans.setLastch4alarmstatus(AlarmStatus[2]);
                trans.setLastco2alarmstatus(AlarmStatus[3]);
                trans.setLastc2h4alarmstatus(AlarmStatus[4]);
                trans.setLastc2h2alarmstatus(AlarmStatus[5]);
                trans.setLastc2h6alarmstatus(AlarmStatus[6]);
                trans.setLasttothydalarmstatus(AlarmStatus[7]);
                trans.setLastppmalarmstatus(AlarmStatus[8]);
                // trans.setLasto2alarmstatus(AlarmStatus[9]);
                // trans.setLastn2alarmstatus(AlarmStatus[10]);
                trans.setLastalarmlevel(HexUtil.MAX(AlarmStatus));
                trans.setLastalarmmessage(alarmMessage);
                if (oilserviceimpl.Update(trans, false) == 0) {
                    setText(languageManager.getLan().getUpdateRealtimeDataFailedCheckDatabaseConnection());
                }

                Oilhistory transhis = new Oilhistory();
                transhis.setStationid(trans.getStationid());
                transhis.setDevicegroup(trans.getDevicegroup());
                transhis.setDeviceaddr(trans.getDeviceaddr());
                transhis.setPointname(trans.getPointname());
                transhis.setH2(trans.getLasth2());
                transhis.setCo(trans.getLastco());
                transhis.setCh4(trans.getLastch4());
                transhis.setCo2(trans.getLastco2());
                transhis.setC2h4(trans.getLastc2h4());
                transhis.setC2h2(trans.getLastc2h2());
                transhis.setC2h6(trans.getLastc2h6());
                transhis.setTothyd(trans.getLasttothyd());
                transhis.setPpm(trans.getLastppm());
                // transhis.setO2(trans.getLasto2());
                // transhis.setN2(trans.getLastn2());
                transhis.setDatatime(trans.getLastdatatime());
                transhis.setAlarmlevel(trans.getLastalarmlevel());
                transhis.setAlarmmessage(trans.getLastalarmmessage());
                transhis.setCommunicationstatus(trans.getLastcommunicationstatus());
                if (oilserviceimpl.Add(transhis) == 0) {
                    setText("添加历史数据失败，请检查数据库连接");
                }

                str2.append("【设备返回数据：】");
                str2.append(" 电站地址：" + 1);
                str2.append(" 设备地址：" + (i) + "\r\n");
                str2.append(" 氢气：" + H2 + "\r\n");
                str2.append(" 一氧化碳：" + CO + "\r\n");
                str2.append(" 甲烷：" + CH4 + "\r\n");
                str2.append(" 二氧化碳：" + CO2 + "" + "\r\n");
                str2.append(" 乙烯：" + C2H4 + "\r\n");
                str2.append(" 乙炔：" + C2H2 + "\r\n");
                str2.append(" 乙烷：" + C2H6 + "\r\n");
                str2.append(" 总烃：" + TotHyd + "" + "\r\n");
                str2.append(" 微水：" + PPM + "\r\n");
                // str2.append(" 氧气：" + O2 + "\r\n");
                // str2.append(" 氮气：" + N2 + "\r\n");
                setText(str2.toString());
            }
            Thread.sleep(timersp);
        }
    }

    private void UpdateAndAdd(Oilsensor trans, Oilsensor target, boolean simulate, int overcount) {
        StringBuilder str2 = new StringBuilder();
        String alarmMessage = "";// '报警消息
        int AlarmStatus[] = new int[11];
        if (trans.getH2warnvalue() == null || trans.getCowarnvalue() == null || trans.getCh4warnvalue() == null
                || trans.getCo2warnvalue() == null || trans.getC2h4warnvalue() == null
                || trans.getC2h2warnvalue() == null || trans.getC2h6warnvalue() == null
                || trans.getTothydwarnvalue() == null || trans.getPpmalarmvalue() == null
                || trans.getO2warnvalue() == null || trans.getN2alarmvalue() == null
                || trans.getH2warnvalue() == null || trans.getCoalarmvalue() == null
                || trans.getCh4alarmvalue() == null || trans.getCo2alarmvalue() == null
                || trans.getC2h4alarmvalue() == null || trans.getC2h2alarmvalue() == null
                || trans.getC2h6alarmvalue() == null || trans.getTothydalarmvalue() == null
                || trans.getPpmalarmvalue() == null
                || trans.getO2alarmvalue() == null
                || trans.getN2alarmvalue() == null) {
            setText(languageManager.getLan().getCurrentMonitoringPoint() + (trans.getDeviceaddr()) + " "
                    + languageManager.getLan().getAlarmValueNotSet() + "！");
            return;
        }

        AlarmStatus[0] = GetAlarmStatus(isnull(target.getLasth2()), trans.getH2alarmvalue(),
                trans.getH2alarmrelievevalue(),
                trans.getH2warnvalue(), trans.getH2warnrelievevalue(), trans.getLasth2alarmstatus(), true,
                languageManager.getLan().getHydrogen(),
                trans.getDevicegroup(), trans.getDeviceaddr(), trans.getPointname());
        AlarmStatus[1] = GetAlarmStatus(isnull(target.getLastco()), trans.getCoalarmvalue(),
                trans.getCoalarmrelievevalue(),
                trans.getCowarnvalue(), trans.getCowarnvalue(), trans.getLastcoalarmstatus(), true,
                languageManager.getLan().getCarbonMonoxide(),
                trans.getDevicegroup(), trans.getDeviceaddr(), trans.getPointname());
        AlarmStatus[2] = GetAlarmStatus(isnull(target.getLastch4()), trans.getCh4alarmvalue(),
                trans.getCh4alarmrelievevalue(),
                trans.getCh4warnvalue(), trans.getCh4warnrelievevalue(), trans.getLastch4alarmstatus(), true,
                languageManager.getLan().getMethane(),
                trans.getDevicegroup(), trans.getDeviceaddr(), trans.getPointname());
        AlarmStatus[3] = GetAlarmStatus(isnull(target.getLastco2()), trans.getCo2alarmvalue(),
                trans.getCo2alarmrelievevalue(),
                trans.getCo2warnvalue(), trans.getCo2warnrelievevalue(), trans.getLastco2alarmstatus(), true,
                languageManager.getLan().getCarbonDioxide(),
                trans.getDevicegroup(), trans.getDeviceaddr(), trans.getPointname());
        AlarmStatus[4] = GetAlarmStatus(isnull(target.getLastc2h4()), trans.getC2h4alarmvalue(),
                trans.getC2h4alarmrelievevalue(),
                trans.getC2h4warnvalue(), trans.getC2h4warnrelievevalue(), trans.getLastc2h4alarmstatus(), true,
                languageManager.getLan().getEthylene(),
                trans.getDevicegroup(), trans.getDeviceaddr(), trans.getPointname());
        AlarmStatus[5] = GetAlarmStatus(isnull(target.getLastc2h2()), trans.getC2h2alarmvalue(),
                trans.getC2h2alarmrelievevalue(),
                trans.getC2h2warnvalue(), trans.getC2h2warnrelievevalue(), trans.getLastc2h2alarmstatus(), true,
                languageManager.getLan().getAcetylene(),
                trans.getDevicegroup(), trans.getDeviceaddr(), trans.getPointname());
        AlarmStatus[6] = GetAlarmStatus(isnull(target.getLastc2h6()), trans.getC2h6alarmvalue(),
                trans.getC2h6alarmrelievevalue(),
                trans.getC2h6warnvalue(), trans.getC2h6warnrelievevalue(), trans.getLastc2h6alarmstatus(), true,
                languageManager.getLan().getEthane(),
                trans.getDevicegroup(), trans.getDeviceaddr(), trans.getPointname());
        AlarmStatus[7] = GetAlarmStatus(isnull(target.getLasttothyd()), trans.getTothydalarmvalue(),
                trans.getTothydalarmrelievevalue(),
                trans.getTothydwarnvalue(), trans.getTothydwarnrelievevalue(), trans.getLasttothydalarmstatus(),
                true, languageManager.getLan().getTotalHydrocarbon(), trans.getDevicegroup(), trans.getDeviceaddr(),
                trans.getPointname());
        AlarmStatus[8] = GetAlarmStatus(isnull(target.getLastppm()), trans.getPpmalarmvalue(),
                trans.getPpmalarmrelievevalue(),
                trans.getPpmwarnvalue(), trans.getPpmwarnrelievevalue(), trans.getLastppmalarmstatus(), true,
                languageManager.getLan().getMoisture(),
                trans.getDevicegroup(), trans.getDeviceaddr(), trans.getPointname());
        AlarmStatus[9] = GetAlarmStatus(isnull(trans.getLasto2()),
                trans.getO2alarmvalue(), trans.getO2alarmrelievevalue(),
                trans.getO2warnvalue(),
                trans.getO2warnrelievevalue(), trans.getLasto2alarmstatus(), true, languageManager.getLan().getOxygen(),
                trans.getDevicegroup(),
                trans.getDeviceaddr(), trans.getPointname());
        AlarmStatus[10] = GetAlarmStatus(isnull(trans.getLastn2()),
                trans.getN2alarmvalue(), trans.getN2alarmrelievevalue(),
                trans.getN2warnvalue(),
                trans.getN2warnrelievevalue(), trans.getLastn2alarmstatus(), true,
                languageManager.getLan().getNitrogen(),
                trans.getDevicegroup(),
                trans.getDeviceaddr(), trans.getPointname());
        // 报警消息
        alarmMessage += GetAlarmMessage(AlarmStatus[0], languageManager.getLan().getHydrogen());
        alarmMessage += GetAlarmMessage(AlarmStatus[1], languageManager.getLan().getCarbonMonoxide());
        alarmMessage += GetAlarmMessage(AlarmStatus[2], languageManager.getLan().getMethane());
        alarmMessage += GetAlarmMessage(AlarmStatus[3], languageManager.getLan().getCarbonDioxide());
        alarmMessage += GetAlarmMessage(AlarmStatus[4], languageManager.getLan().getEthylene());
        alarmMessage += GetAlarmMessage(AlarmStatus[5], languageManager.getLan().getAcetylene());
        alarmMessage += GetAlarmMessage(AlarmStatus[6], languageManager.getLan().getEthane());
        alarmMessage += GetAlarmMessage(AlarmStatus[7], languageManager.getLan().getTotalHydrocarbon());
        alarmMessage += GetAlarmMessage(AlarmStatus[8], languageManager.getLan().getMoisture());
        alarmMessage += GetAlarmMessage(AlarmStatus[9], languageManager.getLan().getOxygen());
        alarmMessage += GetAlarmMessage(AlarmStatus[10], languageManager.getLan().getNitrogen());
        target.setLasth2alarmstatus(AlarmStatus[0]);
        target.setLastcoalarmstatus(AlarmStatus[1]);
        target.setLastch4alarmstatus(AlarmStatus[2]);
        target.setLastco2alarmstatus(AlarmStatus[3]);
        target.setLastc2h4alarmstatus(AlarmStatus[4]);
        target.setLastc2h2alarmstatus(AlarmStatus[5]);
        target.setLastc2h6alarmstatus(AlarmStatus[6]);
        target.setLasttothydalarmstatus(AlarmStatus[7]);
        target.setLastppmalarmstatus(AlarmStatus[8]);
        target.setLasto2alarmstatus(AlarmStatus[9]);
        target.setLastn2alarmstatus(AlarmStatus[10]);
        target.setLastalarmlevel(HexUtil.MAX(AlarmStatus));
        target.setLastalarmmessage(alarmMessage);
        target.setCount(trans.getCount() + 1);
        if (target.getCount() > overcount) {
            if ((target.getLasth2() != 0 && target.getLastco() == 0)
                    || (target.getLasth2() == 0 && target.getLastco() != 0)
                    || (target.getLastco2() > 1000) || (target.getLastco() > 500)
                    || target.getLastalarmlevel() == 2) {
                if (simulate && trans.getSimulateauto() != 0) {
                    Oilsensor oils = new Oilsensor();
                    oils.setStationid(ad.getStationid());
                    oils.setDevicegroup(ad.getDevicegroup());
                    oils.setDeviceaddr(trans.getDeviceaddr());
                    simfun(trans.getDeviceaddr());
                    oils.setLastorigindata(simulatestr.toString());
                    oilserviceimpl.Update(oils, false);
                    dataTransform(trans.getDeviceaddr(), false);
                    return;
                }
            }
        }

        if (oilserviceimpl.Update(target, false) == 0) {
            setText(languageManager.getLan().getUpdateRealtimeDataFailedCheckDatabaseConnection());
        }

        Oilhistory transhis = new Oilhistory();
        transhis.setStationid(trans.getStationid());
        transhis.setDevicegroup(trans.getDevicegroup());
        transhis.setDeviceaddr(trans.getDeviceaddr());
        transhis.setPointname(trans.getPointname());
        transhis.setH2(target.getLasth2());
        transhis.setCo(target.getLastco());
        transhis.setCh4(target.getLastch4());
        transhis.setCo2(target.getLastco2());
        transhis.setC2h4(target.getLastc2h4());
        transhis.setC2h2(target.getLastc2h2());
        transhis.setC2h6(target.getLastc2h6());
        transhis.setTothyd(target.getLasttothyd());
        if (target.getLastppm() == null) {
            transhis.setPpm(trans.getLastppm());
        } else {
            transhis.setPpm(target.getLastppm());
        }
        transhis.setO2(target.getLasto2());
        transhis.setN2(target.getLastn2());
        transhis.setDatatime(target.getLastdatatime());
        transhis.setAlarmlevel(target.getLastalarmlevel());
        transhis.setAlarmmessage(target.getLastalarmmessage());
        transhis.setElem(target.getLastelem());
        transhis.setProcesseddata(target.getLastprocesseddata());
        transhis.setCommunicationstatus(target.getLastcommunicationstatus());
        if (oilserviceimpl.Add(transhis) == 0) {
            setText(languageManager.getLan().getAddHistoricalDataFailedCheckDatabaseConnection());
        }

        str2.append("【" + languageManager.getLan().getDeviceReturnedData() + "：】");
        str2.append(" " + languageManager.getLan().getStationID() + "：" + target.getStationid());
        str2.append(" " + languageManager.getLan().getDeviceAddress() + "：" + target.getDeviceaddr() + "\r\n");
        str2.append(" " + languageManager.getLan().getHydrogen() + "：" + target.getLasth2() + "\r\n");
        str2.append(" " + languageManager.getLan().getCarbonMonoxide() + "：" + target.getLastco() + "\r\n");
        str2.append(" " + languageManager.getLan().getMethane() + "：" + target.getLastch4() + "\r\n");
        str2.append(" " + languageManager.getLan().getCarbonDioxide() + "：" + target.getLastco2() + "" + "\r\n");
        str2.append(" " + languageManager.getLan().getEthylene() + "：" + target.getLastc2h4() + "\r\n");
        str2.append(" " + languageManager.getLan().getEthane() + "：" + target.getLastc2h6() + "\r\n");
        str2.append(" " + languageManager.getLan().getAcetylene() + "：" + target.getLastc2h2() + "\r\n");
        str2.append(" " + languageManager.getLan().getTotalHydrocarbon() + "：" + target.getLasttothyd() + "" + "\r\n");
        str2.append(" " + languageManager.getLan().getMoisture() + "：" + target.getLastppm() + "\r\n");
        str2.append(" " + languageManager.getLan().getOxygen() + "：" + target.getLasto2() + "\r\n");
        str2.append(" " + languageManager.getLan().getNitrogen() + "：" + target.getLastn2() + "\r\n");
        setText(str2.toString());
    }

    public void curve(int[][] dxy, int[] wind, int wind2, int wind3, boolean display) {
        try {
            int start = wind[0];
            int end = wind[1];
            Random rd = new Random();
            int height = (int) (wind[2] * 1.02 + (rd.nextInt(10000) - 3000));
            int[][] bp = { dxy[start], dxy[end] };
            int[][] xy = { bp[0], { (end - start) / 2 + start, height }, bp[1] };
            double tmpx1 = xy[0][0] - xy[1][0];
            double tmpx2 = xy[2][0] - xy[1][0];
            double tmpy1 = xy[0][1] - xy[1][1];
            double tmpy2 = xy[2][1] - xy[1][1];
            BigDecimal tpyf1 = new BigDecimal((tmpx1 * tmpx1 + tmpy1 * tmpy1) + "");
            BigDecimal tpyf2 = new BigDecimal((tmpx2 * tmpx2 + tmpy2 * tmpy2) + "");
            MathContext mc = new MathContext(10);
            double dist1 = tpyf1.sqrt(mc).doubleValue();
            double dist2 = tpyf2.sqrt(mc).doubleValue();
            if (dist1 == 0 || dist2 == 0) {
                dist1 = 1;
                dist2 = 1;
            }
            BigDecimal dtmp1 = new BigDecimal((dist1 * dist2) + "");
            double tmpx = xy[1][0] - dtmp1.sqrt(mc).longValue() * (tmpx1 / dist1 + tmpx2 / dist2) / 2;
            double tmpy = xy[1][1] - dtmp1.sqrt(mc).longValue() * (tmpy1 / dist1 + tmpy2 / dist2) / 2;
            xy[1][0] = (int) tmpx;
            xy[1][1] = (int) tmpy;
            int[][] dxy1 = bezier(xy, end - start);
            for (int i = wind2; i < start; i++) {
                simulatestr.append(dxy[i][1] + ",");
            }
            if (display) {
                for (int i = start; i < end; i++) {
                    dxy1[i - start][1] = dxy1[i - start][1] + rd.nextInt(150) - 75;
                    simulatestr.append(dxy1[i - start][1] + ",");
                }
            } else {
                for (int i = start; i < end; i++) {
                    simulatestr.append(dxy[i][1] + ",");
                }
            }
            for (int i = end; i < wind3; i++) {
                simulatestr.append(dxy[i][1] + ",");
            }
        } catch (Exception e) {
            logger.info(e.toString());
        }
    }

    public void simfun(int addrint) {
        Example example = new Example(Oilconfig.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("stationid", ad.getStationid());
        criteria.andEqualTo("devicegroup", ad.getDevicegroup());
        criteria.andEqualTo("deviceaddr", addrint);
        List<Oilconfig> ol = oilconfigmapper.selectByExample(example);
        if (ol == null || ol.size() == 0) {
            setText("" + languageManager.getLan().getAddress() + "<" + addrint + ">"
                    + languageManager.getLan().getConfigurationInformationMissing() + "！！");
            return;
        }

        Random rd = new Random();
        int y1 = 130000 - rd.nextInt(3000);
        int y6 = 116000 - rd.nextInt(3000);
        int[][] xy = { { 0, y1 }, { 314, 127000 }, { 1459, 121500 }, { 1905, 120000 }, { 8300, 116000 },
                { wBKPara[addrint] * 20, y6 } };// 基线定点
        int[][] dxy = bezier(xy, wBKPara[addrint] * 20);// 基线贝塞尔走线趋势
        int[][] wind = { { 0, 1, y1 },
                { ol.get(0).getStart().intValue() + rd.nextInt(50) + 50,
                        (int) ol.get(0).getStart().intValue() + rd.nextInt(100) + 250,
                        dxy[ol.get(0).getStart().intValue() / 2 + (int) ol.get(0).getEnd().intValue() / 2][1]
                                + Float.valueOf(ol.get(0).getOilstandard() * 1000f).intValue() },
                { ol.get(1).getStart().intValue() + rd.nextInt(50) + 50,
                        (int) ol.get(1).getStart().intValue() + rd.nextInt(100) + 250,
                        dxy[ol.get(1).getStart().intValue() / 2 + (int) ol.get(1).getEnd().intValue() / 2][1]
                                + Float.valueOf(ol.get(1).getOilstandard() * 1000f).intValue() },
                { ol.get(2).getStart().intValue() + rd.nextInt(50) + 50,
                        (int) ol.get(2).getStart().intValue() + rd.nextInt(100) + 250,
                        dxy[ol.get(2).getStart().intValue() / 2 + (int) ol.get(2).getEnd().intValue() / 2][1]
                                + Float.valueOf(ol.get(2).getOilstandard() * 1000f).intValue() },
                { ol.get(3).getStart().intValue() + rd.nextInt(50) + 50,
                        (int) ol.get(3).getStart().intValue() + rd.nextInt(100) + 250,
                        dxy[ol.get(3).getStart().intValue() / 2 + (int) ol.get(3).getEnd().intValue() / 2][1]
                                + Float.valueOf(ol.get(3).getOilstandard() * 1000f).intValue() },
                { ol.get(4).getStart().intValue() + rd.nextInt(50) + 50,
                        (int) ol.get(4).getStart().intValue() + rd.nextInt(100) + 250,
                        dxy[ol.get(4).getStart().intValue() / 2 + (int) ol.get(4).getEnd().intValue() / 2][1]
                                + Float.valueOf(ol.get(4).getOilstandard() * 1000f).intValue() },
                { ol.get(5).getStart().intValue() + rd.nextInt(50) + 50,
                        (int) ol.get(5).getStart().intValue() + rd.nextInt(100) + 250,
                        dxy[ol.get(5).getStart().intValue() / 2 + (int) ol.get(5).getEnd().intValue() / 2][1]
                                + Float.valueOf(ol.get(5).getOilstandard() * 1000f).intValue() },
                { ol.get(6).getStart().intValue() + rd.nextInt(50) + 50,
                        (int) ol.get(6).getStart().intValue() + rd.nextInt(100) + 250,
                        dxy[ol.get(6).getStart().intValue() / 2 + (int) ol.get(6).getEnd().intValue() / 2][1]
                                + Float.valueOf(ol.get(6).getOilstandard() * 1000f).intValue() },
                { wBKPara[addrint] * 20 - 1, wBKPara[addrint] * 20 - 1, y6 } };//
        int i = 1;
        curve(dxy, wind[0], 0, wind[i][0], false);// 填补
        curve(dxy, wind[1], wind[i++][0], wind[i][0], f_H2 != 0);// h2
        curve(dxy, wind[2], wind[i++][0], wind[i][0], f_CO != 0);// co
        curve(dxy, wind[3], wind[i++][0], wind[i][0], f_CH4 != 0);// ch4
        curve(dxy, wind[4], wind[i++][0], wind[i][0], f_CO2 != 0);// co2
        curve(dxy, wind[5], wind[i++][0], wind[i][0], f_C2H4 != 0);// c2h4
        curve(dxy, wind[6], wind[i++][0], wind[i][0], f_C2H6 != 0);// c2h6
        curve(dxy, wind[7], wind[i++][0], wind[i][0], f_C2H2 != 0);// c2h2
        curve(dxy, wind[8], wind[i++][0], dxy.length, false);// 填补

        Oilsensor os = new Oilsensor();
        os.setStationid(ad.getStationid());
        os.setDevicegroup(ad.getDevicegroup());
        os.setDeviceaddr(addrint);
        os.setLastorigindata(simulatestr.toString());
        if (oilserviceimpl.Update(os, false) == 0) {
            setText(languageManager.getLan().getUpdateGraphFailed()
                    + languageManager.getLan().getNoMonitoringPointInDatabase()
                    + (addrint)
                    + " ！ "
                    + languageManager.getLan().getPleaseAddMonitoringPointFirst()
                    + "！");
            return;
        }
    }
}
